]> git.ipfire.org Git - thirdparty/linux.git/blame - tools/perf/util/quote.c
License cleanup: add SPDX GPL-2.0 license identifier to files with no license
[thirdparty/linux.git] / tools / perf / util / quote.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
a43783ae 2#include <errno.h>
380a71a2
ACM
3#include <stdlib.h>
4#include "strbuf.h"
07800601 5#include "quote.h"
380a71a2 6#include "util.h"
07800601 7
07800601
IM
8/* Help to copy the thing properly quoted for the shell safety.
9 * any single quote is replaced with '\'', any exclamation point
10 * is replaced with '\!', and the whole thing is enclosed in a
11 *
12 * E.g.
13 * original sq_quote result
14 * name ==> name ==> 'name'
15 * a b ==> a b ==> 'a b'
16 * a'b ==> a'\''b ==> 'a'\''b'
17 * a!b ==> a'\!'b ==> 'a'\!'b'
18 */
19static inline int need_bs_quote(char c)
20{
21 return (c == '\'' || c == '!');
22}
23
70a6898f 24static int sq_quote_buf(struct strbuf *dst, const char *src)
07800601
IM
25{
26 char *to_free = NULL;
70a6898f 27 int ret;
07800601
IM
28
29 if (dst->buf == src)
30 to_free = strbuf_detach(dst, NULL);
31
70a6898f
MH
32 ret = strbuf_addch(dst, '\'');
33 while (!ret && *src) {
07800601 34 size_t len = strcspn(src, "'!");
70a6898f 35 ret = strbuf_add(dst, src, len);
07800601 36 src += len;
70a6898f
MH
37 while (!ret && need_bs_quote(*src))
38 ret = strbuf_addf(dst, "'\\%c\'", *src++);
07800601 39 }
70a6898f
MH
40 if (!ret)
41 ret = strbuf_addch(dst, '\'');
07800601 42 free(to_free);
70a6898f
MH
43
44 return ret;
07800601
IM
45}
46
70a6898f 47int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
07800601 48{
70a6898f 49 int i, ret;
07800601
IM
50
51 /* Copy into destination buffer. */
70a6898f
MH
52 ret = strbuf_grow(dst, 255);
53 for (i = 0; !ret && argv[i]; ++i) {
54 ret = strbuf_addch(dst, ' ');
55 if (ret)
56 break;
57 ret = sq_quote_buf(dst, argv[i]);
07800601 58 if (maxlen && dst->len > maxlen)
e7b32d12 59 return -ENOSPC;
07800601 60 }
70a6898f 61 return ret;
07800601 62}