| 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 | |
| 25 | /* |
| 26 | * Fallback for systems which don't have fmemopen. Copy buffer to a |
| 27 | * temporary file, and use that file as FILE * input. |
| 28 | */ |
| 29 | static inline |
| 30 | FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) |
| 31 | { |
| 32 | char tmpname[PATH_MAX]; |
| 33 | size_t len; |
| 34 | FILE *fp; |
| 35 | int ret; |
| 36 | |
| 37 | /* |
| 38 | * Support reading only. |
| 39 | */ |
| 40 | if (strcmp(mode, "rb") != 0) { |
| 41 | return NULL; |
| 42 | } |
| 43 | strncpy(tmpname, "/tmp/lttng-tmp-XXXXXX", PATH_MAX); |
| 44 | ret = mkstemp(tmpname); |
| 45 | if (ret < 0) { |
| 46 | return NULL; |
| 47 | } |
| 48 | /* |
| 49 | * We need to write to the file. |
| 50 | */ |
| 51 | fp = fdopen(ret, "w+"); |
| 52 | if (!fp) { |
| 53 | goto error_unlink; |
| 54 | } |
| 55 | /* Copy the entire buffer to the file */ |
| 56 | len = fwrite(buf, sizeof(char), size, fp); |
| 57 | if (len != size) { |
| 58 | goto error_close; |
| 59 | } |
| 60 | ret = fseek(fp, 0L, SEEK_SET); |
| 61 | if (ret < 0) { |
| 62 | PERROR("fseek"); |
| 63 | goto error_close; |
| 64 | } |
| 65 | /* We keep the handle open, but can unlink the file on the VFS. */ |
| 66 | ret = unlink(tmpname); |
| 67 | if (ret < 0) { |
| 68 | PERROR("unlink"); |
| 69 | } |
| 70 | return fp; |
| 71 | |
| 72 | error_close: |
| 73 | ret = fclose(fp); |
| 74 | if (ret < 0) { |
| 75 | PERROR("close"); |
| 76 | } |
| 77 | error_unlink: |
| 78 | ret = unlink(tmpname); |
| 79 | if (ret < 0) { |
| 80 | PERROR("unlink"); |
| 81 | } |
| 82 | return NULL; |
| 83 | } |
| 84 | |
| 85 | #endif /* LTTNG_HAVE_FMEMOPEN */ |
| 86 | |
| 87 | #endif /* _LTTNG_CTL_MEMSTREAM_H */ |