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