| 1 | /* |
| 2 | * Copyright (C) 2020 Jérémie Galarneau <jeremie.galarneau@efficios.com> |
| 3 | * |
| 4 | * SPDX-License-Identifier: LGPL-2.1-only |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #include "payload.h" |
| 9 | #include <common/dynamic-array.h> |
| 10 | #include <common/dynamic-buffer.h> |
| 11 | #include <common/error.h> |
| 12 | |
| 13 | LTTNG_HIDDEN |
| 14 | void lttng_payload_init(struct lttng_payload *payload) |
| 15 | { |
| 16 | assert(payload); |
| 17 | lttng_dynamic_buffer_init(&payload->buffer); |
| 18 | lttng_dynamic_array_init(&payload->_fds, sizeof(int), NULL); |
| 19 | } |
| 20 | |
| 21 | LTTNG_HIDDEN |
| 22 | int lttng_payload_copy(const struct lttng_payload *src_payload, |
| 23 | struct lttng_payload *dst_payload) |
| 24 | { |
| 25 | int ret; |
| 26 | size_t i; |
| 27 | |
| 28 | ret = lttng_dynamic_buffer_append_buffer( |
| 29 | &dst_payload->buffer, &src_payload->buffer); |
| 30 | if (ret) { |
| 31 | goto error; |
| 32 | } |
| 33 | |
| 34 | for (i = 0; i < lttng_dynamic_array_get_count(&src_payload->_fds); |
| 35 | i++) { |
| 36 | int dst_fd; |
| 37 | const int src_fd = *((int *) lttng_dynamic_array_get_element( |
| 38 | &src_payload->_fds, i)); |
| 39 | |
| 40 | dst_fd = dup(src_fd); |
| 41 | if (dst_fd < 0) { |
| 42 | PERROR("Failed to duplicate file descriptor while copying a payload"); |
| 43 | ret = dst_fd; |
| 44 | goto error; |
| 45 | } |
| 46 | |
| 47 | ret = lttng_payload_push_fd(dst_payload, dst_fd); |
| 48 | if (ret) { |
| 49 | const int close_ret = close(dst_fd); |
| 50 | |
| 51 | if (close_ret < 0) { |
| 52 | PERROR("Failed to close duplicated file descriptor while copying a payload"); |
| 53 | } |
| 54 | |
| 55 | goto error; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | end: |
| 60 | return ret; |
| 61 | error: |
| 62 | goto end; |
| 63 | } |
| 64 | |
| 65 | LTTNG_HIDDEN |
| 66 | void lttng_payload_reset(struct lttng_payload *payload) |
| 67 | { |
| 68 | if (!payload) { |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | lttng_dynamic_buffer_reset(&payload->buffer); |
| 73 | lttng_dynamic_array_reset(&payload->_fds); |
| 74 | } |
| 75 | |
| 76 | LTTNG_HIDDEN |
| 77 | int lttng_payload_push_fd(struct lttng_payload *payload, int fd) |
| 78 | { |
| 79 | int ret; |
| 80 | |
| 81 | if (!payload) { |
| 82 | ret = -1; |
| 83 | goto end; |
| 84 | } |
| 85 | |
| 86 | ret = lttng_dynamic_array_add_element(&payload->_fds, &fd); |
| 87 | end: |
| 88 | return ret; |
| 89 | } |