| 1 | #ifndef _LTTNG_CTL_MEMSTREAM_H |
| 2 | #define _LTTNG_CTL_MEMSTREAM_H |
| 3 | |
| 4 | /* |
| 5 | * src/lib/lttng-ctl/memstream.h |
| 6 | * |
| 7 | * Copyright 2012 (c) - Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 8 | * |
| 9 | * memstream compatibility layer. |
| 10 | * |
| 11 | * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 12 | * of this software and associated documentation files (the "Software"), to deal |
| 13 | * in the Software without restriction, including without limitation the rights |
| 14 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 15 | * copies of the Software, and to permit persons to whom the Software is |
| 16 | * furnished to do so, subject to the following conditions: |
| 17 | * |
| 18 | * The above copyright notice and this permission notice shall be included in |
| 19 | * all copies or substantial portions of the Software. |
| 20 | */ |
| 21 | |
| 22 | #ifdef LTTNG_HAVE_FMEMOPEN |
| 23 | #include <stdio.h> |
| 24 | |
| 25 | static inline |
| 26 | FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) |
| 27 | { |
| 28 | return fmemopen(buf, size, mode); |
| 29 | } |
| 30 | |
| 31 | #else /* LTTNG_HAVE_FMEMOPEN */ |
| 32 | |
| 33 | #include <stdlib.h> |
| 34 | #include <stdio.h> |
| 35 | |
| 36 | /* |
| 37 | * Fallback for systems which don't have fmemopen. Copy buffer to a |
| 38 | * temporary file, and use that file as FILE * input. |
| 39 | */ |
| 40 | static inline |
| 41 | FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) |
| 42 | { |
| 43 | char tmpname[PATH_MAX]; |
| 44 | size_t len; |
| 45 | FILE *fp; |
| 46 | int ret; |
| 47 | |
| 48 | /* |
| 49 | * Support reading only. |
| 50 | */ |
| 51 | if (strcmp(mode, "rb") != 0) { |
| 52 | return NULL; |
| 53 | } |
| 54 | strncpy(tmpname, "/tmp/lttng-tmp-XXXXXX", PATH_MAX); |
| 55 | ret = mkstemp(tmpname); |
| 56 | if (ret < 0) { |
| 57 | return NULL; |
| 58 | } |
| 59 | /* |
| 60 | * We need to write to the file. |
| 61 | */ |
| 62 | fp = fdopen(ret, "w+"); |
| 63 | if (!fp) { |
| 64 | goto error_unlink; |
| 65 | } |
| 66 | /* Copy the entire buffer to the file */ |
| 67 | len = fwrite(buf, sizeof(char), size, fp); |
| 68 | if (len != size) { |
| 69 | goto error_close; |
| 70 | } |
| 71 | ret = fseek(fp, 0L, SEEK_SET); |
| 72 | if (ret < 0) { |
| 73 | PERROR("fseek"); |
| 74 | goto error_close; |
| 75 | } |
| 76 | /* We keep the handle open, but can unlink the file on the VFS. */ |
| 77 | ret = unlink(tmpname); |
| 78 | if (ret < 0) { |
| 79 | PERROR("unlink"); |
| 80 | } |
| 81 | return fp; |
| 82 | |
| 83 | error_close: |
| 84 | ret = fclose(fp); |
| 85 | if (ret < 0) { |
| 86 | PERROR("close"); |
| 87 | } |
| 88 | error_unlink: |
| 89 | ret = unlink(tmpname); |
| 90 | if (ret < 0) { |
| 91 | PERROR("unlink"); |
| 92 | } |
| 93 | return NULL; |
| 94 | } |
| 95 | |
| 96 | #endif /* LTTNG_HAVE_FMEMOPEN */ |
| 97 | |
| 98 | #endif /* _LTTNG_CTL_MEMSTREAM_H */ |