X-Git-Url: http://git.efficios.com/?p=lttng-tools.git;a=blobdiff_plain;f=src%2Fcommon%2Ffilter%2Fmemstream.h;fp=src%2Fcommon%2Ffilter%2Fmemstream.h;h=cd246eed27e9a8a4e032b3be40ccb1ecc3aaf50c;hp=0000000000000000000000000000000000000000;hb=1831ae68b70dece8e9b847081526495adbbf05e5;hpb=25357057de5ae4dd2a572e8f9b893c1b90cbd60a diff --git a/src/common/filter/memstream.h b/src/common/filter/memstream.h new file mode 100644 index 000000000..cd246eed2 --- /dev/null +++ b/src/common/filter/memstream.h @@ -0,0 +1,87 @@ +/* + * Copyright 2012 (C) Mathieu Desnoyers + * + * SPDX-License-Identifier: MIT + * + */ + +#ifndef _LTTNG_CTL_MEMSTREAM_H +#define _LTTNG_CTL_MEMSTREAM_H + +#ifdef LTTNG_HAVE_FMEMOPEN +#include + +static inline +FILE *lttng_fmemopen(void *buf, size_t size, const char *mode) +{ + return fmemopen(buf, size, mode); +} + +#else /* LTTNG_HAVE_FMEMOPEN */ + +#include +#include + +/* + * 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) +{ + char tmpname[PATH_MAX]; + size_t len; + FILE *fp; + int ret; + + /* + * Support reading only. + */ + if (strcmp(mode, "rb") != 0) { + return NULL; + } + strncpy(tmpname, "/tmp/lttng-tmp-XXXXXX", PATH_MAX); + ret = mkstemp(tmpname); + if (ret < 0) { + return NULL; + } + /* + * We need to write to the file. + */ + fp = fdopen(ret, "w+"); + if (!fp) { + goto error_unlink; + } + /* Copy the entire buffer to the file */ + len = fwrite(buf, sizeof(char), size, fp); + if (len != size) { + goto error_close; + } + ret = fseek(fp, 0L, SEEK_SET); + if (ret < 0) { + PERROR("fseek"); + goto error_close; + } + /* We keep the handle open, but can unlink the file on the VFS. */ + ret = unlink(tmpname); + if (ret < 0) { + PERROR("unlink"); + } + return fp; + +error_close: + ret = fclose(fp); + if (ret < 0) { + PERROR("close"); + } +error_unlink: + ret = unlink(tmpname); + if (ret < 0) { + PERROR("unlink"); + } + return NULL; +} + +#endif /* LTTNG_HAVE_FMEMOPEN */ + +#endif /* _LTTNG_CTL_MEMSTREAM_H */