| 1 | /* |
| 2 | * Copyright 2012 (C) Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 3 | * |
| 4 | * SPDX-License-Identifier: MIT |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #ifndef _LTTNG_CTL_MEMSTREAM_H |
| 9 | #define _LTTNG_CTL_MEMSTREAM_H |
| 10 | |
| 11 | #ifdef LTTNG_HAVE_FMEMOPEN |
| 12 | #include <stdio.h> |
| 13 | |
| 14 | static inline |
| 15 | FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) |
| 16 | { |
| 17 | return fmemopen(buf, size, mode); |
| 18 | } |
| 19 | |
| 20 | #else /* LTTNG_HAVE_FMEMOPEN */ |
| 21 | |
| 22 | #include <stdlib.h> |
| 23 | #include <stdio.h> |
| 24 | #include <common/error.h> |
| 25 | |
| 26 | /* |
| 27 | * Fallback for systems which don't have fmemopen. Copy buffer to a |
| 28 | * temporary file, and use that file as FILE * input. |
| 29 | */ |
| 30 | static inline |
| 31 | FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) |
| 32 | { |
| 33 | char tmpname[PATH_MAX]; |
| 34 | size_t len; |
| 35 | FILE *fp; |
| 36 | int ret; |
| 37 | |
| 38 | /* |
| 39 | * Support reading only. |
| 40 | */ |
| 41 | if (strcmp(mode, "rb") != 0) { |
| 42 | return NULL; |
| 43 | } |
| 44 | strncpy(tmpname, "/tmp/lttng-tmp-XXXXXX", PATH_MAX); |
| 45 | ret = mkstemp(tmpname); |
| 46 | if (ret < 0) { |
| 47 | return NULL; |
| 48 | } |
| 49 | /* |
| 50 | * We need to write to the file. |
| 51 | */ |
| 52 | fp = fdopen(ret, "w+"); |
| 53 | if (!fp) { |
| 54 | goto error_unlink; |
| 55 | } |
| 56 | /* Copy the entire buffer to the file */ |
| 57 | len = fwrite(buf, sizeof(char), size, fp); |
| 58 | if (len != size) { |
| 59 | goto error_close; |
| 60 | } |
| 61 | ret = fseek(fp, 0L, SEEK_SET); |
| 62 | if (ret < 0) { |
| 63 | PERROR("fseek"); |
| 64 | goto error_close; |
| 65 | } |
| 66 | /* We keep the handle open, but can unlink the file on the VFS. */ |
| 67 | ret = unlink(tmpname); |
| 68 | if (ret < 0) { |
| 69 | PERROR("unlink"); |
| 70 | } |
| 71 | return fp; |
| 72 | |
| 73 | error_close: |
| 74 | ret = fclose(fp); |
| 75 | if (ret < 0) { |
| 76 | PERROR("close"); |
| 77 | } |
| 78 | error_unlink: |
| 79 | ret = unlink(tmpname); |
| 80 | if (ret < 0) { |
| 81 | PERROR("unlink"); |
| 82 | } |
| 83 | return NULL; |
| 84 | } |
| 85 | |
| 86 | #endif /* LTTNG_HAVE_FMEMOPEN */ |
| 87 | |
| 88 | #endif /* _LTTNG_CTL_MEMSTREAM_H */ |