Merge tag 'arm64-perf' of git://git.kernel.org/pub/scm/linux/kernel/git/arm64/linux
[linux-2.6-block.git] / tools / perf / util / quote.c
1 #include "cache.h"
2 #include "quote.h"
3
4 /* Help to copy the thing properly quoted for the shell safety.
5  * any single quote is replaced with '\'', any exclamation point
6  * is replaced with '\!', and the whole thing is enclosed in a
7  *
8  * E.g.
9  *  original     sq_quote     result
10  *  name     ==> name      ==> 'name'
11  *  a b      ==> a b       ==> 'a b'
12  *  a'b      ==> a'\''b    ==> 'a'\''b'
13  *  a!b      ==> a'\!'b    ==> 'a'\!'b'
14  */
15 static inline int need_bs_quote(char c)
16 {
17         return (c == '\'' || c == '!');
18 }
19
20 static int sq_quote_buf(struct strbuf *dst, const char *src)
21 {
22         char *to_free = NULL;
23         int ret;
24
25         if (dst->buf == src)
26                 to_free = strbuf_detach(dst, NULL);
27
28         ret = strbuf_addch(dst, '\'');
29         while (!ret && *src) {
30                 size_t len = strcspn(src, "'!");
31                 ret = strbuf_add(dst, src, len);
32                 src += len;
33                 while (!ret && need_bs_quote(*src))
34                         ret = strbuf_addf(dst, "'\\%c\'", *src++);
35         }
36         if (!ret)
37                 ret = strbuf_addch(dst, '\'');
38         free(to_free);
39
40         return ret;
41 }
42
43 int sq_quote_argv(struct strbuf *dst, const char** argv, size_t maxlen)
44 {
45         int i, ret;
46
47         /* Copy into destination buffer. */
48         ret = strbuf_grow(dst, 255);
49         for (i = 0; !ret && argv[i]; ++i) {
50                 ret = strbuf_addch(dst, ' ');
51                 if (ret)
52                         break;
53                 ret = sq_quote_buf(dst, argv[i]);
54                 if (maxlen && dst->len > maxlen)
55                         die("Too many or long arguments");
56         }
57         return ret;
58 }