xref: /linux/kernel/trace/trace_probe.c (revision 665159e246749578d4e4bfe106ee3b74edcdab18)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Common code for probe-based Dynamic events.
4  *
5  * This code was copied from kernel/trace/trace_kprobe.c written by
6  * Masami Hiramatsu <masami.hiramatsu.pt@hitachi.com>
7  *
8  * Updates to make this generic:
9  * Copyright (C) IBM Corporation, 2010-2011
10  * Author:     Srikar Dronamraju
11  */
12 #define pr_fmt(fmt)	"trace_probe: " fmt
13 
14 #include <linux/bpf.h>
15 #include <linux/fs.h>
16 
17 #include "trace_btf.h"
18 #include "trace_probe.h"
19 
20 #undef C
21 #define C(a, b)		b
22 
23 static const char *trace_probe_err_text[] = { ERRORS };
24 
25 static const char *reserved_field_names[] = {
26 	"common_type",
27 	"common_flags",
28 	"common_preempt_count",
29 	"common_pid",
30 	"common_tgid",
31 	FIELD_STRING_IP,
32 	FIELD_STRING_RETIP,
33 	FIELD_STRING_FUNC,
34 };
35 
36 /* Printing  in basic type function template */
37 #define DEFINE_BASIC_PRINT_TYPE_FUNC(tname, type, fmt)			\
38 int PRINT_TYPE_FUNC_NAME(tname)(struct trace_seq *s, void *data, void *ent)\
39 {									\
40 	trace_seq_printf(s, fmt, *(type *)data);			\
41 	return !trace_seq_has_overflowed(s);				\
42 }									\
43 const char PRINT_TYPE_FMT_NAME(tname)[] = fmt;
44 
45 DEFINE_BASIC_PRINT_TYPE_FUNC(u8,  u8,  "%u")
46 DEFINE_BASIC_PRINT_TYPE_FUNC(u16, u16, "%u")
47 DEFINE_BASIC_PRINT_TYPE_FUNC(u32, u32, "%u")
48 DEFINE_BASIC_PRINT_TYPE_FUNC(u64, u64, "%Lu")
49 DEFINE_BASIC_PRINT_TYPE_FUNC(s8,  s8,  "%d")
50 DEFINE_BASIC_PRINT_TYPE_FUNC(s16, s16, "%d")
51 DEFINE_BASIC_PRINT_TYPE_FUNC(s32, s32, "%d")
52 DEFINE_BASIC_PRINT_TYPE_FUNC(s64, s64, "%Ld")
53 DEFINE_BASIC_PRINT_TYPE_FUNC(x8,  u8,  "0x%x")
54 DEFINE_BASIC_PRINT_TYPE_FUNC(x16, u16, "0x%x")
55 DEFINE_BASIC_PRINT_TYPE_FUNC(x32, u32, "0x%x")
56 DEFINE_BASIC_PRINT_TYPE_FUNC(x64, u64, "0x%Lx")
57 DEFINE_BASIC_PRINT_TYPE_FUNC(char, u8, "'%c'")
58 
PRINT_TYPE_FUNC_NAME(symbol)59 int PRINT_TYPE_FUNC_NAME(symbol)(struct trace_seq *s, void *data, void *ent)
60 {
61 	trace_seq_printf(s, "%pS", (void *)*(unsigned long *)data);
62 	return !trace_seq_has_overflowed(s);
63 }
64 const char PRINT_TYPE_FMT_NAME(symbol)[] = "%pS";
65 
66 /* Print type function for string type */
PRINT_TYPE_FUNC_NAME(string)67 int PRINT_TYPE_FUNC_NAME(string)(struct trace_seq *s, void *data, void *ent)
68 {
69 	int len = *(u32 *)data >> 16;
70 
71 	if (!len)
72 		trace_seq_puts(s, FAULT_STRING);
73 	else
74 		trace_seq_printf(s, "\"%s\"",
75 				 (const char *)get_loc_data(data, ent));
76 	return !trace_seq_has_overflowed(s);
77 }
78 
79 const char PRINT_TYPE_FMT_NAME(string)[] = "\\\"%s\\\"";
80 
81 /* Fetch type information table */
82 static const struct fetch_type probe_fetch_types[] = {
83 	/* Special types */
84 	__ASSIGN_FETCH_TYPE("string", string, string, sizeof(u32), 1, 1,
85 			    "__data_loc char[]"),
86 	__ASSIGN_FETCH_TYPE("ustring", string, string, sizeof(u32), 1, 1,
87 			    "__data_loc char[]"),
88 	__ASSIGN_FETCH_TYPE("symstr", string, string, sizeof(u32), 1, 1,
89 			    "__data_loc char[]"),
90 	/* Basic types */
91 	ASSIGN_FETCH_TYPE(u8,  u8,  0),
92 	ASSIGN_FETCH_TYPE(u16, u16, 0),
93 	ASSIGN_FETCH_TYPE(u32, u32, 0),
94 	ASSIGN_FETCH_TYPE(u64, u64, 0),
95 	ASSIGN_FETCH_TYPE(s8,  u8,  1),
96 	ASSIGN_FETCH_TYPE(s16, u16, 1),
97 	ASSIGN_FETCH_TYPE(s32, u32, 1),
98 	ASSIGN_FETCH_TYPE(s64, u64, 1),
99 	ASSIGN_FETCH_TYPE_ALIAS(x8,  u8,  u8,  0),
100 	ASSIGN_FETCH_TYPE_ALIAS(x16, u16, u16, 0),
101 	ASSIGN_FETCH_TYPE_ALIAS(x32, u32, u32, 0),
102 	ASSIGN_FETCH_TYPE_ALIAS(x64, u64, u64, 0),
103 	ASSIGN_FETCH_TYPE_ALIAS(char, u8, u8,  0),
104 	ASSIGN_FETCH_TYPE_ALIAS(symbol, ADDR_FETCH_TYPE, ADDR_FETCH_TYPE, 0),
105 
106 	ASSIGN_FETCH_TYPE_END
107 };
108 
find_fetch_type(const char * type,unsigned long flags)109 static const struct fetch_type *find_fetch_type(const char *type, unsigned long flags)
110 {
111 	int i;
112 
113 	/* Reject the symbol/symstr for uprobes */
114 	if (type && (flags & TPARG_FL_USER) &&
115 	    (!strcmp(type, "symbol") || !strcmp(type, "symstr")))
116 		return NULL;
117 
118 	if (!type)
119 		type = DEFAULT_FETCH_TYPE_STR;
120 
121 	/* Special case: bitfield */
122 	if (*type == 'b') {
123 		unsigned long bs;
124 
125 		type = strchr(type, '/');
126 		if (!type)
127 			goto fail;
128 
129 		type++;
130 		if (kstrtoul(type, 0, &bs))
131 			goto fail;
132 
133 		switch (bs) {
134 		case 8:
135 			return find_fetch_type("u8", flags);
136 		case 16:
137 			return find_fetch_type("u16", flags);
138 		case 32:
139 			return find_fetch_type("u32", flags);
140 		case 64:
141 			return find_fetch_type("u64", flags);
142 		default:
143 			goto fail;
144 		}
145 	}
146 
147 	for (i = 0; probe_fetch_types[i].name; i++) {
148 		if (strcmp(type, probe_fetch_types[i].name) == 0)
149 			return &probe_fetch_types[i];
150 	}
151 
152 fail:
153 	return NULL;
154 }
155 
156 static struct trace_probe_log trace_probe_log;
157 extern struct mutex dyn_event_ops_mutex;
158 
trace_probe_log_init(const char * subsystem,int argc,const char ** argv)159 const char *trace_probe_log_init(const char *subsystem, int argc, const char **argv)
160 {
161 	lockdep_assert_held(&dyn_event_ops_mutex);
162 
163 	trace_probe_log.subsystem = subsystem;
164 	trace_probe_log.argc = argc;
165 	trace_probe_log.argv = argv;
166 	trace_probe_log.index = 0;
167 	return subsystem;
168 }
169 
trace_probe_log_clear(void)170 void trace_probe_log_clear(void)
171 {
172 	lockdep_assert_held(&dyn_event_ops_mutex);
173 
174 	memset(&trace_probe_log, 0, sizeof(trace_probe_log));
175 }
176 
trace_probe_log_set_index(int index)177 void trace_probe_log_set_index(int index)
178 {
179 	lockdep_assert_held(&dyn_event_ops_mutex);
180 
181 	trace_probe_log.index = index;
182 }
183 
__trace_probe_log_err(int offset,int err_type)184 void __trace_probe_log_err(int offset, int err_type)
185 {
186 	char *command, *p;
187 	int i, len = 0, pos = 0;
188 
189 	lockdep_assert_held(&dyn_event_ops_mutex);
190 
191 	if (!trace_probe_log.argv)
192 		return;
193 
194 	/* Recalculate the length and allocate buffer */
195 	for (i = 0; i < trace_probe_log.argc; i++) {
196 		if (i == trace_probe_log.index)
197 			pos = len;
198 		len += strlen(trace_probe_log.argv[i]) + 1;
199 	}
200 	command = kzalloc(len, GFP_KERNEL);
201 	if (!command)
202 		return;
203 
204 	if (trace_probe_log.index >= trace_probe_log.argc) {
205 		/**
206 		 * Set the error position is next to the last arg + space.
207 		 * Note that len includes the terminal null and the cursor
208 		 * appears at pos + 1.
209 		 */
210 		pos = len;
211 		offset = 0;
212 	}
213 
214 	/* And make a command string from argv array */
215 	p = command;
216 	for (i = 0; i < trace_probe_log.argc; i++) {
217 		len = strlen(trace_probe_log.argv[i]);
218 		memcpy(p, trace_probe_log.argv[i], len);
219 		p[len] = ' ';
220 		p += len + 1;
221 	}
222 	*(p - 1) = '\0';
223 
224 	tracing_log_err(NULL, trace_probe_log.subsystem, command,
225 			trace_probe_err_text, err_type, pos + offset);
226 
227 	kfree(command);
228 }
229 
230 /* Split symbol and offset. */
traceprobe_split_symbol_offset(char * symbol,long * offset)231 int traceprobe_split_symbol_offset(char *symbol, long *offset)
232 {
233 	char *tmp;
234 	int ret;
235 
236 	if (!offset)
237 		return -EINVAL;
238 
239 	tmp = strpbrk(symbol, "+-");
240 	if (tmp) {
241 		ret = kstrtol(tmp, 0, offset);
242 		if (ret)
243 			return ret;
244 		*tmp = '\0';
245 	} else
246 		*offset = 0;
247 
248 	return 0;
249 }
250 
251 /**
252  * traceprobe_parse_event_name() - Parse a string into group and event names
253  * @pevent: A pointer to the string to be parsed.
254  * @pgroup: A pointer to the group name.
255  * @buf:    A buffer to store the parsed group name.
256  * @offset: The offset of the string in the original user command, for logging.
257  *
258  * This parses a string with the format `[GROUP/][EVENT]` or `[GROUP.][EVENT]`
259  * (either GROUP or EVENT or both must be specified).
260  * Since the parsed group name is stored in @buf, the caller must ensure @buf
261  * is at least MAX_EVENT_NAME_LEN bytes.
262  *
263  * Return: 0 on success, or -EINVAL on failure.
264  *
265  * If success, *@pevent is updated to point to the event name part of the
266  * original string, or NULL if there is no event name.
267  * Also, *@pgroup is updated to point to the parsed group which is stored
268  * in @buf, or NULL if there is no group name.
269  */
traceprobe_parse_event_name(const char ** pevent,const char ** pgroup,char * buf,int offset)270 int traceprobe_parse_event_name(const char **pevent, const char **pgroup,
271 				char *buf, int offset)
272 {
273 	const char *slash, *event = *pevent;
274 	int len;
275 
276 	slash = strchr(event, '/');
277 	if (!slash)
278 		slash = strchr(event, '.');
279 
280 	if (slash) {
281 		if (slash == event) {
282 			trace_probe_log_err(offset, NO_GROUP_NAME);
283 			return -EINVAL;
284 		}
285 		if (slash - event + 1 > MAX_EVENT_NAME_LEN) {
286 			trace_probe_log_err(offset, GROUP_TOO_LONG);
287 			return -EINVAL;
288 		}
289 		strscpy(buf, event, slash - event + 1);
290 		if (!is_good_system_name(buf)) {
291 			trace_probe_log_err(offset, BAD_GROUP_NAME);
292 			return -EINVAL;
293 		}
294 		*pgroup = buf;
295 		*pevent = slash + 1;
296 		offset += slash - event + 1;
297 		event = *pevent;
298 	}
299 	len = strlen(event);
300 	if (len == 0) {
301 		if (slash) {
302 			*pevent = NULL;
303 			return 0;
304 		}
305 		trace_probe_log_err(offset, NO_EVENT_NAME);
306 		return -EINVAL;
307 	} else if (len >= MAX_EVENT_NAME_LEN) {
308 		trace_probe_log_err(offset, EVENT_TOO_LONG);
309 		return -EINVAL;
310 	}
311 	if (!is_good_name(event)) {
312 		trace_probe_log_err(offset, BAD_EVENT_NAME);
313 		return -EINVAL;
314 	}
315 	return 0;
316 }
317 
parse_trace_event_arg(char * arg,struct fetch_insn * code,struct traceprobe_parse_context * ctx)318 static int parse_trace_event_arg(char *arg, struct fetch_insn *code,
319 				 struct traceprobe_parse_context *ctx)
320 {
321 	struct ftrace_event_field *field;
322 	struct list_head *head;
323 
324 	head = trace_get_fields(ctx->event);
325 	list_for_each_entry(field, head, link) {
326 		if (!strcmp(arg, field->name)) {
327 			code->op = FETCH_OP_TP_ARG;
328 			code->data = field;
329 			return 0;
330 		}
331 	}
332 	return -ENOENT;
333 }
334 
parse_trace_event(char * arg,struct fetch_insn * code,struct traceprobe_parse_context * ctx)335 static int parse_trace_event(char *arg, struct fetch_insn *code,
336 			     struct traceprobe_parse_context *ctx)
337 {
338 	int ret;
339 
340 	if (code->data)
341 		return -EFAULT;
342 	ret = parse_trace_event_arg(arg, code, ctx);
343 	if (!ret)
344 		return 0;
345 	return -EINVAL;
346 }
347 
348 #ifdef CONFIG_PROBE_EVENTS_BTF_ARGS
349 
btf_type_int(const struct btf_type * t)350 static u32 btf_type_int(const struct btf_type *t)
351 {
352 	return *(u32 *)(t + 1);
353 }
354 
btf_type_is_char_ptr(struct btf * btf,const struct btf_type * type)355 static bool btf_type_is_char_ptr(struct btf *btf, const struct btf_type *type)
356 {
357 	const struct btf_type *real_type;
358 	u32 intdata;
359 	s32 tid;
360 
361 	real_type = btf_type_skip_modifiers(btf, type->type, &tid);
362 	if (!real_type)
363 		return false;
364 
365 	if (BTF_INFO_KIND(real_type->info) != BTF_KIND_INT)
366 		return false;
367 
368 	intdata = btf_type_int(real_type);
369 	return !(BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED)
370 		&& BTF_INT_BITS(intdata) == 8;
371 }
372 
btf_type_is_char_array(struct btf * btf,const struct btf_type * type)373 static bool btf_type_is_char_array(struct btf *btf, const struct btf_type *type)
374 {
375 	const struct btf_type *real_type;
376 	const struct btf_array *array;
377 	u32 intdata;
378 	s32 tid;
379 
380 	if (BTF_INFO_KIND(type->info) != BTF_KIND_ARRAY)
381 		return false;
382 
383 	array = (const struct btf_array *)(type + 1);
384 
385 	real_type = btf_type_skip_modifiers(btf, array->type, &tid);
386 
387 	intdata = btf_type_int(real_type);
388 	return !(BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED)
389 		&& BTF_INT_BITS(intdata) == 8;
390 }
391 
ctx_btf(struct traceprobe_parse_context * ctx)392 static struct btf *ctx_btf(struct traceprobe_parse_context *ctx)
393 {
394 	return ctx->struct_btf ? : ctx->btf;
395 }
396 
check_prepare_btf_string_fetch(char * typename,struct fetch_insn ** pcode,struct traceprobe_parse_context * ctx)397 static int check_prepare_btf_string_fetch(char *typename,
398 				struct fetch_insn **pcode,
399 				struct traceprobe_parse_context *ctx)
400 {
401 	struct btf *btf = ctx_btf(ctx);
402 
403 	if (!btf || !ctx->last_type)
404 		return 0;
405 
406 	/* char [] does not need any change. */
407 	if (btf_type_is_char_array(btf, ctx->last_type))
408 		return 0;
409 
410 	/* char * requires dereference the pointer. */
411 	if (btf_type_is_char_ptr(btf, ctx->last_type)) {
412 		struct fetch_insn *code = *pcode + 1;
413 
414 		if (code->op == FETCH_OP_END) {
415 			trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
416 			return -E2BIG;
417 		}
418 		if (typename[0] == 'u')
419 			code->op = FETCH_OP_UDEREF;
420 		else
421 			code->op = FETCH_OP_DEREF;
422 		code->offset = 0;
423 		*pcode = code;
424 		return 0;
425 	}
426 	/* Other types are not available for string */
427 	trace_probe_log_err(ctx->offset, BAD_TYPE4STR);
428 	return -EINVAL;
429 }
430 
fetch_type_from_btf_type(struct btf * btf,const struct btf_type * type,struct traceprobe_parse_context * ctx)431 static const char *fetch_type_from_btf_type(struct btf *btf,
432 					const struct btf_type *type,
433 					struct traceprobe_parse_context *ctx)
434 {
435 	u32 intdata;
436 
437 	/* TODO: const char * could be converted as a string */
438 	switch (BTF_INFO_KIND(type->info)) {
439 	case BTF_KIND_ENUM:
440 		/* enum is "int", so convert to "s32" */
441 		return "s32";
442 	case BTF_KIND_ENUM64:
443 		return "s64";
444 	case BTF_KIND_PTR:
445 		/* pointer will be converted to "x??" */
446 		if (IS_ENABLED(CONFIG_64BIT))
447 			return "x64";
448 		else
449 			return "x32";
450 	case BTF_KIND_INT:
451 		intdata = btf_type_int(type);
452 		if (BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED) {
453 			switch (BTF_INT_BITS(intdata)) {
454 			case 8:
455 				return "s8";
456 			case 16:
457 				return "s16";
458 			case 32:
459 				return "s32";
460 			case 64:
461 				return "s64";
462 			}
463 		} else {	/* unsigned */
464 			switch (BTF_INT_BITS(intdata)) {
465 			case 8:
466 				return "u8";
467 			case 16:
468 				return "u16";
469 			case 32:
470 				return "u32";
471 			case 64:
472 				return "u64";
473 			}
474 			/* bitfield, size is encoded in the type */
475 			ctx->last_bitsize = BTF_INT_BITS(intdata);
476 			ctx->last_bitoffs += BTF_INT_OFFSET(intdata);
477 			return "u64";
478 		}
479 	}
480 	/* TODO: support other types */
481 
482 	return NULL;
483 }
484 
query_btf_context(struct traceprobe_parse_context * ctx)485 static int query_btf_context(struct traceprobe_parse_context *ctx)
486 {
487 	const struct btf_param *param;
488 	const struct btf_type *type;
489 	struct btf *btf;
490 	s32 nr;
491 
492 	if (ctx->btf)
493 		return 0;
494 
495 	if (!ctx->funcname)
496 		return -EINVAL;
497 
498 	type = btf_find_func_proto(ctx->funcname, &btf);
499 	if (!type)
500 		return -ENOENT;
501 
502 	ctx->btf = btf;
503 	ctx->proto = type;
504 
505 	/* ctx->params is optional, since func(void) will not have params. */
506 	nr = 0;
507 	param = btf_get_func_param(type, &nr);
508 	if (!IS_ERR_OR_NULL(param)) {
509 		/* Hide the first 'data' argument of tracepoint */
510 		if (ctx->flags & TPARG_FL_TPOINT) {
511 			nr--;
512 			param++;
513 		}
514 	}
515 
516 	if (nr > 0) {
517 		ctx->nr_params = nr;
518 		ctx->params = param;
519 	} else {
520 		ctx->nr_params = 0;
521 		ctx->params = NULL;
522 	}
523 
524 	return 0;
525 }
526 
clear_struct_btf(struct traceprobe_parse_context * ctx)527 static void clear_struct_btf(struct traceprobe_parse_context *ctx)
528 {
529 	if (ctx->struct_btf) {
530 		btf_put(ctx->struct_btf);
531 		ctx->struct_btf = NULL;
532 		ctx->last_struct = NULL;
533 	}
534 }
535 
clear_btf_context(struct traceprobe_parse_context * ctx)536 static void clear_btf_context(struct traceprobe_parse_context *ctx)
537 {
538 	if (ctx->btf) {
539 		btf_put(ctx->btf);
540 		ctx->btf = NULL;
541 		ctx->proto = NULL;
542 		ctx->params = NULL;
543 		ctx->nr_params = 0;
544 	}
545 }
546 
547 /* Return 1 if the field separator is arrow operator ('->') */
split_next_field(char * varname,char ** next_field,struct traceprobe_parse_context * ctx)548 static int split_next_field(char *varname, char **next_field,
549 			    struct traceprobe_parse_context *ctx)
550 {
551 	char *field;
552 	int ret = 0;
553 
554 	field = strpbrk(varname, ".-");
555 	if (field) {
556 		if (field[0] == '-' && field[1] == '>') {
557 			field[0] = '\0';
558 			field += 2;
559 			ret = 1;
560 		} else if (field[0] == '.') {
561 			field[0] = '\0';
562 			field += 1;
563 		} else {
564 			trace_probe_log_err(ctx->offset + field - varname, BAD_HYPHEN);
565 			return -EINVAL;
566 		}
567 		*next_field = field;
568 	}
569 
570 	return ret;
571 }
572 
573 /*
574  * Parse the field of data structure. The @type must be a pointer type
575  * pointing the target data structure type.
576  */
parse_btf_field(char * fieldname,const struct btf_type * type,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)577 static int parse_btf_field(char *fieldname, const struct btf_type *type,
578 			   struct fetch_insn **pcode, struct fetch_insn *end,
579 			   struct traceprobe_parse_context *ctx)
580 {
581 	struct fetch_insn *code = *pcode;
582 	const struct btf_member *field;
583 	u32 bitoffs, anon_offs;
584 	bool is_struct = ctx->struct_btf != NULL;
585 	struct btf *btf = ctx_btf(ctx);
586 	char *next;
587 	int is_ptr;
588 	s32 tid;
589 
590 	do {
591 		if (!is_struct) {
592 			/* Outer loop for solving arrow operator ('->') */
593 			if (BTF_INFO_KIND(type->info) != BTF_KIND_PTR) {
594 				trace_probe_log_err(ctx->offset, NO_PTR_STRCT);
595 				return -EINVAL;
596 			}
597 
598 			/* Convert a struct pointer type to a struct type */
599 			type = btf_type_skip_modifiers(btf, type->type, &tid);
600 			if (!type) {
601 				trace_probe_log_err(ctx->offset, BAD_BTF_TID);
602 				return -EINVAL;
603 			}
604 		}
605 		/* Only the first type can skip being a pointer */
606 		is_struct = false;
607 
608 		bitoffs = 0;
609 		do {
610 			/* Inner loop for solving dot operator ('.') */
611 			next = NULL;
612 			is_ptr = split_next_field(fieldname, &next, ctx);
613 			if (is_ptr < 0)
614 				return is_ptr;
615 
616 			anon_offs = 0;
617 			field = btf_find_struct_member(btf, type, fieldname,
618 						       &anon_offs);
619 			if (IS_ERR(field)) {
620 				trace_probe_log_err(ctx->offset, BAD_BTF_TID);
621 				return PTR_ERR(field);
622 			}
623 			if (!field) {
624 				trace_probe_log_err(ctx->offset, NO_BTF_FIELD);
625 				return -ENOENT;
626 			}
627 			/* Add anonymous structure/union offset */
628 			bitoffs += anon_offs;
629 
630 			/* Accumulate the bit-offsets of the dot-connected fields */
631 			if (btf_type_kflag(type)) {
632 				bitoffs += BTF_MEMBER_BIT_OFFSET(field->offset);
633 				ctx->last_bitsize = BTF_MEMBER_BITFIELD_SIZE(field->offset);
634 			} else {
635 				bitoffs += field->offset;
636 				ctx->last_bitsize = 0;
637 			}
638 
639 			type = btf_type_skip_modifiers(btf, field->type, &tid);
640 			if (!type) {
641 				trace_probe_log_err(ctx->offset, BAD_BTF_TID);
642 				return -EINVAL;
643 			}
644 
645 			ctx->offset += next - fieldname;
646 			fieldname = next;
647 		} while (!is_ptr && fieldname);
648 
649 		if (++code == end) {
650 			trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
651 			return -EINVAL;
652 		}
653 		code->op = FETCH_OP_DEREF;	/* TODO: user deref support */
654 		code->offset = bitoffs / 8;
655 		*pcode = code;
656 
657 		ctx->last_bitoffs = bitoffs % 8;
658 		ctx->last_type = type;
659 	} while (fieldname);
660 
661 	return 0;
662 }
663 
664 static int __store_entry_arg(struct trace_probe *tp, int argnum);
665 
parse_btf_arg(char * varname,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)666 static int parse_btf_arg(char *varname,
667 			 struct fetch_insn **pcode, struct fetch_insn *end,
668 			 struct traceprobe_parse_context *ctx)
669 {
670 	struct fetch_insn *code = *pcode;
671 	const struct btf_param *params;
672 	const struct btf_type *type;
673 	char *field = NULL;
674 	int i, is_ptr, ret;
675 	u32 tid;
676 
677 	if (!ctx->funcname && !(ctx->flags & TPARG_FL_TEVENT))
678 		return -EINVAL;
679 
680 	is_ptr = split_next_field(varname, &field, ctx);
681 	if (is_ptr < 0)
682 		return is_ptr;
683 	if (!is_ptr && field) {
684 		/* dot-connected field on an argument is not supported. */
685 		trace_probe_log_err(ctx->offset + field - varname,
686 				    NOSUP_DAT_ARG);
687 		return -EOPNOTSUPP;
688 	}
689 
690 	if (ctx->flags & TPARG_FL_TEVENT) {
691 		ret = parse_trace_event(varname, code, ctx);
692 		if (ret < 0) {
693 			trace_probe_log_err(ctx->offset, BAD_ATTACH_ARG);
694 			return ret;
695 		}
696 		/* TEVENT is only here via a typecast */
697 		if (WARN_ON_ONCE(ctx->struct_btf == NULL))
698 			return -EINVAL;
699 		type = ctx->last_struct;
700 		goto found_type;
701 	}
702 
703 	if (ctx->flags & TPARG_FL_RETURN && !strcmp(varname, "$retval")) {
704 		code->op = FETCH_OP_RETVAL;
705 		/* Check whether the function return type is not void */
706 		if (query_btf_context(ctx) == 0) {
707 			if (ctx->proto->type == 0) {
708 				trace_probe_log_err(ctx->offset, NO_RETVAL);
709 				return -ENOENT;
710 			}
711 			tid = ctx->proto->type;
712 			goto found;
713 		}
714 		if (field) {
715 			trace_probe_log_err(ctx->offset + field - varname,
716 					    NO_BTF_ENTRY);
717 			return -ENOENT;
718 		}
719 		return 0;
720 	}
721 
722 	if (!ctx->btf) {
723 		ret = query_btf_context(ctx);
724 		if (ret < 0 || ctx->nr_params == 0) {
725 			trace_probe_log_err(ctx->offset, NO_BTF_ENTRY);
726 			return -ENOENT;
727 		}
728 	}
729 	params = ctx->params;
730 
731 	for (i = 0; i < ctx->nr_params; i++) {
732 		const char *name = btf_name_by_offset(ctx->btf, params[i].name_off);
733 
734 		if (name && !strcmp(name, varname)) {
735 			if (tparg_is_function_entry(ctx->flags)) {
736 				code->op = FETCH_OP_ARG;
737 				if (ctx->flags & TPARG_FL_TPOINT)
738 					code->param = i + 1;
739 				else
740 					code->param = i;
741 			} else if (tparg_is_function_return(ctx->flags)) {
742 				code->op = FETCH_OP_EDATA;
743 				ret = __store_entry_arg(ctx->tp, i);
744 				if (ret < 0) {
745 					/* internal error */
746 					return ret;
747 				}
748 				code->offset = ret;
749 			}
750 			tid = params[i].type;
751 			goto found;
752 		}
753 	}
754 	trace_probe_log_err(ctx->offset, NO_BTFARG);
755 	return -ENOENT;
756 
757 found:
758 	type = btf_type_skip_modifiers(ctx->btf, tid, &tid);
759 found_type:
760 	if (!type) {
761 		trace_probe_log_err(ctx->offset, BAD_BTF_TID);
762 		return -EINVAL;
763 	}
764 	/* Initialize the last type information */
765 	ctx->last_type = type;
766 	ctx->last_bitoffs = 0;
767 	ctx->last_bitsize = 0;
768 	if (field) {
769 		ctx->offset += field - varname;
770 		return parse_btf_field(field, type, pcode, end, ctx);
771 	}
772 	return 0;
773 }
774 
find_fetch_type_from_btf_type(struct traceprobe_parse_context * ctx)775 static const struct fetch_type *find_fetch_type_from_btf_type(
776 					struct traceprobe_parse_context *ctx)
777 {
778 	struct btf *btf = ctx_btf(ctx);
779 	const char *typestr = NULL;
780 
781 	if (btf && ctx->last_type)
782 		typestr = fetch_type_from_btf_type(btf, ctx->last_type, ctx);
783 
784 	return find_fetch_type(typestr, ctx->flags);
785 }
786 
parse_btf_bitfield(struct fetch_insn ** pcode,struct traceprobe_parse_context * ctx)787 static int parse_btf_bitfield(struct fetch_insn **pcode,
788 			      struct traceprobe_parse_context *ctx)
789 {
790 	struct fetch_insn *code = *pcode;
791 
792 	if ((ctx->last_bitsize % 8 == 0) && ctx->last_bitoffs == 0)
793 		return 0;
794 
795 	code++;
796 	if (code->op != FETCH_OP_NOP) {
797 		trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
798 		return -EINVAL;
799 	}
800 	*pcode = code;
801 
802 	code->op = FETCH_OP_MOD_BF;
803 	code->lshift = 64 - (ctx->last_bitsize + ctx->last_bitoffs);
804 	code->rshift = 64 - ctx->last_bitsize;
805 	code->basesize = 64 / 8;
806 	return 0;
807 }
808 
query_btf_struct(const char * sname,struct traceprobe_parse_context * ctx)809 static int query_btf_struct(const char *sname, struct traceprobe_parse_context *ctx)
810 {
811 	struct btf *btf = NULL;
812 	int id;
813 
814 	/* A struct_btf should only be used by a single argument */
815 	if (WARN_ON_ONCE(ctx->struct_btf)) {
816 		btf_put(ctx->struct_btf);
817 		ctx->struct_btf = NULL;
818 	}
819 
820 	id = bpf_find_btf_id(sname, BTF_KIND_STRUCT, &btf);
821 	if (id < 0)
822 		return id;
823 	ctx->struct_btf = btf;
824 	ctx->last_struct = btf_type_by_id(ctx->struct_btf, id);
825 	return 0;
826 }
827 
handle_typecast(char * arg,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)828 static int handle_typecast(char *arg, struct fetch_insn **pcode,
829 			   struct fetch_insn *end,
830 			   struct traceprobe_parse_context *ctx)
831 {
832 	char *tmp;
833 	int ret;
834 
835 	/* Currently this only works for eprobes */
836 	if (!(ctx->flags & TPARG_FL_TEVENT)) {
837 		trace_probe_log_err(ctx->offset, TYPECAST_NOT_EVENT);
838 		return -EINVAL;
839 	}
840 
841 	tmp = strchr(arg, ')');
842 	if (!tmp) {
843 		trace_probe_log_err(ctx->offset + strlen(arg),
844 				    DEREF_OPEN_BRACE);
845 		return -EINVAL;
846 	}
847 	*tmp = '\0';
848 	ret = query_btf_struct(arg + 1, ctx);
849 	*tmp = ')';
850 
851 	if (ret < 0) {
852 		trace_probe_log_err(ctx->offset + 1, NO_PTR_STRCT);
853 		return -EINVAL;
854 	}
855 
856 	tmp++;
857 
858 	ctx->offset += tmp - arg;
859 	ret = parse_btf_arg(tmp, pcode, end, ctx);
860 	return ret;
861 }
862 
863 #else /* !CONFIG_PROBE_EVENTS_BTF_ARGS */
864 
clear_struct_btf(struct traceprobe_parse_context * ctx)865 static void clear_struct_btf(struct traceprobe_parse_context *ctx)
866 {
867 	ctx->struct_btf = NULL;
868 }
869 
clear_btf_context(struct traceprobe_parse_context * ctx)870 static void clear_btf_context(struct traceprobe_parse_context *ctx)
871 {
872 	ctx->btf = NULL;
873 }
874 
query_btf_context(struct traceprobe_parse_context * ctx)875 static int query_btf_context(struct traceprobe_parse_context *ctx)
876 {
877 	return -EOPNOTSUPP;
878 }
879 
parse_btf_arg(char * varname,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)880 static int parse_btf_arg(char *varname,
881 			 struct fetch_insn **pcode, struct fetch_insn *end,
882 			 struct traceprobe_parse_context *ctx)
883 {
884 	trace_probe_log_err(ctx->offset, NOSUP_BTFARG);
885 	return -EOPNOTSUPP;
886 }
887 
parse_btf_bitfield(struct fetch_insn ** pcode,struct traceprobe_parse_context * ctx)888 static int parse_btf_bitfield(struct fetch_insn **pcode,
889 			      struct traceprobe_parse_context *ctx)
890 {
891 	trace_probe_log_err(ctx->offset, NOSUP_BTFARG);
892 	return -EOPNOTSUPP;
893 }
894 
895 #define find_fetch_type_from_btf_type(ctx)		\
896 	find_fetch_type(NULL, ctx->flags)
897 
check_prepare_btf_string_fetch(char * typename,struct fetch_insn ** pcode,struct traceprobe_parse_context * ctx)898 static int check_prepare_btf_string_fetch(char *typename,
899 				struct fetch_insn **pcode,
900 				struct traceprobe_parse_context *ctx)
901 {
902 	return 0;
903 }
904 
handle_typecast(char * arg,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)905 static int handle_typecast(char *arg, struct fetch_insn **pcode,
906 			   struct fetch_insn *end,
907 			   struct traceprobe_parse_context *ctx)
908 {
909 	trace_probe_log_err(ctx->offset, NOSUP_BTFARG);
910 	return -EOPNOTSUPP;
911 }
912 
913 #endif /* CONFIG_PROBE_EVENTS_BTF_ARGS */
914 
915 #ifdef CONFIG_HAVE_FUNCTION_ARG_ACCESS_API
916 
store_entry_arg_at(struct fetch_insn * code,int argnum,int offset)917 static void store_entry_arg_at(struct fetch_insn *code, int argnum, int offset)
918 {
919 	code[0].op = FETCH_OP_ARG;
920 	code[0].param = argnum;
921 	code[1].op = FETCH_OP_ST_EDATA;
922 	code[1].offset = offset;
923 }
924 
get_entry_arg_max_offset(struct probe_entry_arg * earg)925 static int get_entry_arg_max_offset(struct probe_entry_arg *earg)
926 {
927 	int i, max_offset = 0;
928 
929 	/*
930 	 * earg->code[] array has an operation sequence which is run in
931 	 * the entry handler.
932 	 * The sequence stopped by FETCH_OP_END and each data stored in
933 	 * the entry data buffer by FETCH_OP_ST_EDATA. The FETCH_OP_ST_EDATA
934 	 * stores the data at the data buffer + its offset, and all data are
935 	 * "unsigned long" size. The offset must be increased when a data is
936 	 * stored. Thus we need to find the last FETCH_OP_ST_EDATA in the
937 	 * code array.
938 	 */
939 	for (i = 0; i < earg->size - 1 && earg->code[i].op != FETCH_OP_END; i++) {
940 		if (earg->code[i].op == FETCH_OP_ST_EDATA)
941 			if (earg->code[i].offset > max_offset)
942 				max_offset = earg->code[i].offset;
943 	}
944 	return max_offset;
945 }
946 
947 /*
948  * Add the entry code to store the 'argnum'th parameter and return the offset
949  * in the entry data buffer where the data will be stored.
950  */
__store_entry_arg(struct trace_probe * tp,int argnum)951 static int __store_entry_arg(struct trace_probe *tp, int argnum)
952 {
953 	struct probe_entry_arg *earg = tp->entry_arg;
954 	int i, offset, last_offset = 0;
955 
956 	if (!earg) {
957 		earg = kzalloc_flex(*earg, code, 2 * tp->nr_args + 1);
958 		if (!earg)
959 			return -ENOMEM;
960 		earg->size = 2 * tp->nr_args + 1;
961 		/* Fill the code buffer with 'end' to simplify it */
962 		for (i = 0; i < earg->size; i++)
963 			earg->code[i].op = FETCH_OP_END;
964 		tp->entry_arg = earg;
965 		store_entry_arg_at(earg->code, argnum, 0);
966 		return 0;
967 	}
968 
969 	/*
970 	 * NOTE: if anyone change the following rule, please rewrite this.
971 	 * The entry code array is filled with the pair of
972 	 *
973 	 * [FETCH_OP_ARG(argnum)]
974 	 * [FETCH_OP_ST_EDATA(offset of entry data buffer)]
975 	 *
976 	 * and the rest of entries are filled with [FETCH_OP_END].
977 	 * The offset should be incremented, thus the last pair should
978 	 * have the largest offset.
979 	 */
980 
981 	/* Search the offset for the sprcified argnum. */
982 	for (i = 0; i < earg->size - 1 && earg->code[i].op != FETCH_OP_END; i += 2) {
983 		if (WARN_ON_ONCE(earg->code[i].op != FETCH_OP_ARG))
984 			return -EINVAL;
985 
986 		if (earg->code[i].param != argnum)
987 			continue;
988 
989 		if (WARN_ON_ONCE(earg->code[i + 1].op != FETCH_OP_ST_EDATA))
990 			return -EINVAL;
991 
992 		return earg->code[i + 1].offset;
993 	}
994 	/* Not found, append new entry if possible. */
995 	if (i >= earg->size - 1)
996 		return -ENOSPC;
997 
998 	/* The last entry must have the largest offset. */
999 	if (i != 0) {
1000 		if (WARN_ON_ONCE(earg->code[i - 1].op != FETCH_OP_ST_EDATA))
1001 			return -EINVAL;
1002 		last_offset = earg->code[i - 1].offset;
1003 	}
1004 
1005 	offset = last_offset + sizeof(unsigned long);
1006 	store_entry_arg_at(&earg->code[i], argnum, offset);
1007 	return offset;
1008 }
1009 
traceprobe_get_entry_data_size(struct trace_probe * tp)1010 int traceprobe_get_entry_data_size(struct trace_probe *tp)
1011 {
1012 	struct probe_entry_arg *earg = tp->entry_arg;
1013 
1014 	if (!earg)
1015 		return 0;
1016 
1017 	return get_entry_arg_max_offset(earg) + sizeof(unsigned long);
1018 }
1019 
store_trace_entry_data(void * edata,struct trace_probe * tp,struct pt_regs * regs)1020 void store_trace_entry_data(void *edata, struct trace_probe *tp, struct pt_regs *regs)
1021 {
1022 	struct probe_entry_arg *earg = tp->entry_arg;
1023 	unsigned long val = 0;
1024 	int i;
1025 
1026 	if (!earg)
1027 		return;
1028 
1029 	for (i = 0; i < earg->size; i++) {
1030 		struct fetch_insn *code = &earg->code[i];
1031 
1032 		switch (code->op) {
1033 		case FETCH_OP_ARG:
1034 			val = regs_get_kernel_argument(regs, code->param);
1035 			break;
1036 		case FETCH_OP_ST_EDATA:
1037 			*(unsigned long *)((unsigned long)edata + code->offset) = val;
1038 			break;
1039 		case FETCH_OP_END:
1040 			goto end;
1041 		default:
1042 			break;
1043 		}
1044 	}
1045 end:
1046 	return;
1047 }
NOKPROBE_SYMBOL(store_trace_entry_data)1048 NOKPROBE_SYMBOL(store_trace_entry_data)
1049 #endif
1050 
1051 #define PARAM_MAX_STACK (THREAD_SIZE / sizeof(unsigned long))
1052 
1053 /* Parse $vars. @orig_arg points '$', which syncs to @ctx->offset */
1054 static int parse_probe_vars(char *orig_arg, const struct fetch_type *t,
1055 			    struct fetch_insn **pcode,
1056 			    struct fetch_insn *end,
1057 			    struct traceprobe_parse_context *ctx)
1058 {
1059 	struct fetch_insn *code = *pcode;
1060 	int err = TP_ERR_BAD_VAR;
1061 	char *arg = orig_arg + 1;
1062 	unsigned long param;
1063 	int ret = 0;
1064 	int len;
1065 
1066 	if (ctx->flags & TPARG_FL_TEVENT) {
1067 		if (parse_trace_event(arg, code, ctx) < 0) {
1068 			/* 'comm' should be checked after field parsing. */
1069 			if (strcmp(arg, "comm") == 0 || strcmp(arg, "COMM") == 0) {
1070 				code->op = FETCH_OP_COMM;
1071 				return 0;
1072 			}
1073 			goto inval;
1074 		}
1075 		return 0;
1076 	}
1077 
1078 	if (str_has_prefix(arg, "retval")) {
1079 		if (!(ctx->flags & TPARG_FL_RETURN)) {
1080 			err = TP_ERR_RETVAL_ON_PROBE;
1081 			goto inval;
1082 		}
1083 		if (!(ctx->flags & TPARG_FL_KERNEL) ||
1084 		    !IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS)) {
1085 			code->op = FETCH_OP_RETVAL;
1086 			return 0;
1087 		}
1088 		return parse_btf_arg(orig_arg, pcode, end, ctx);
1089 	}
1090 
1091 	len = str_has_prefix(arg, "stack");
1092 	if (len) {
1093 
1094 		if (arg[len] == '\0') {
1095 			code->op = FETCH_OP_STACKP;
1096 			return 0;
1097 		}
1098 
1099 		if (isdigit(arg[len])) {
1100 			ret = kstrtoul(arg + len, 10, &param);
1101 			if (ret)
1102 				goto inval;
1103 
1104 			if ((ctx->flags & TPARG_FL_KERNEL) &&
1105 			    param > PARAM_MAX_STACK) {
1106 				err = TP_ERR_BAD_STACK_NUM;
1107 				goto inval;
1108 			}
1109 			code->op = FETCH_OP_STACK;
1110 			code->param = (unsigned int)param;
1111 			return 0;
1112 		}
1113 		goto inval;
1114 	}
1115 
1116 	if (strcmp(arg, "comm") == 0 || strcmp(arg, "COMM") == 0) {
1117 		code->op = FETCH_OP_COMM;
1118 		return 0;
1119 	}
1120 
1121 #ifdef CONFIG_HAVE_FUNCTION_ARG_ACCESS_API
1122 	len = str_has_prefix(arg, "arg");
1123 	if (len) {
1124 		ret = kstrtoul(arg + len, 10, &param);
1125 		if (ret)
1126 			goto inval;
1127 
1128 		if (!param || param > PARAM_MAX_STACK) {
1129 			err = TP_ERR_BAD_ARG_NUM;
1130 			goto inval;
1131 		}
1132 		param--; /* argN starts from 1, but internal arg[N] starts from 0 */
1133 
1134 		if (tparg_is_function_entry(ctx->flags)) {
1135 			code->op = FETCH_OP_ARG;
1136 			code->param = (unsigned int)param;
1137 			/*
1138 			 * The tracepoint probe will probe a stub function, and the
1139 			 * first parameter of the stub is a dummy and should be ignored.
1140 			 */
1141 			if (ctx->flags & TPARG_FL_TPOINT)
1142 				code->param++;
1143 		} else if (tparg_is_function_return(ctx->flags)) {
1144 			/* function entry argument access from return probe */
1145 			ret = __store_entry_arg(ctx->tp, param);
1146 			if (ret < 0)	/* This error should be an internal error */
1147 				return ret;
1148 
1149 			code->op = FETCH_OP_EDATA;
1150 			code->offset = ret;
1151 		} else {
1152 			err = TP_ERR_NOFENTRY_ARGS;
1153 			goto inval;
1154 		}
1155 		return 0;
1156 	}
1157 #endif
1158 
1159 inval:
1160 	__trace_probe_log_err(ctx->offset, err);
1161 	return -EINVAL;
1162 }
1163 
str_to_immediate(char * str,unsigned long * imm)1164 static int str_to_immediate(char *str, unsigned long *imm)
1165 {
1166 	if (isdigit(str[0]))
1167 		return kstrtoul(str, 0, imm);
1168 	else if (str[0] == '-')
1169 		return kstrtol(str, 0, (long *)imm);
1170 	else if (str[0] == '+')
1171 		return kstrtol(str + 1, 0, (long *)imm);
1172 	return -EINVAL;
1173 }
1174 
__parse_imm_string(char * str,char ** pbuf,int offs)1175 static int __parse_imm_string(char *str, char **pbuf, int offs)
1176 {
1177 	size_t len = strlen(str);
1178 
1179 	if (!len || str[len - 1] != '"') {
1180 		trace_probe_log_err(offs + len, IMMSTR_NO_CLOSE);
1181 		return -EINVAL;
1182 	}
1183 	*pbuf = kstrndup(str, len - 1, GFP_KERNEL);
1184 	if (!*pbuf)
1185 		return -ENOMEM;
1186 	return 0;
1187 }
1188 
1189 /* Recursive argument parser */
1190 static int
parse_probe_arg(char * arg,const struct fetch_type * type,struct fetch_insn ** pcode,struct fetch_insn * end,struct traceprobe_parse_context * ctx)1191 parse_probe_arg(char *arg, const struct fetch_type *type,
1192 		struct fetch_insn **pcode, struct fetch_insn *end,
1193 		struct traceprobe_parse_context *ctx)
1194 {
1195 	struct fetch_insn *code = *pcode;
1196 	unsigned long param;
1197 	int deref = FETCH_OP_DEREF;
1198 	long offset = 0;
1199 	char *tmp;
1200 	int ret = 0;
1201 
1202 	switch (arg[0]) {
1203 	case '$':
1204 		ret = parse_probe_vars(arg, type, pcode, end, ctx);
1205 		break;
1206 
1207 	case '%':	/* named register */
1208 		if (ctx->flags & (TPARG_FL_TEVENT | TPARG_FL_FPROBE)) {
1209 			/* eprobe and fprobe do not handle registers */
1210 			trace_probe_log_err(ctx->offset, BAD_VAR);
1211 			break;
1212 		}
1213 		ret = regs_query_register_offset(arg + 1);
1214 		if (ret >= 0) {
1215 			code->op = FETCH_OP_REG;
1216 			code->param = (unsigned int)ret;
1217 			ret = 0;
1218 		} else
1219 			trace_probe_log_err(ctx->offset, BAD_REG_NAME);
1220 		break;
1221 
1222 	case '@':	/* memory, file-offset or symbol */
1223 		if (isdigit(arg[1])) {
1224 			ret = kstrtoul(arg + 1, 0, &param);
1225 			if (ret) {
1226 				trace_probe_log_err(ctx->offset, BAD_MEM_ADDR);
1227 				break;
1228 			}
1229 			/* load address */
1230 			code->op = FETCH_OP_IMM;
1231 			code->immediate = param;
1232 		} else if (arg[1] == '+') {
1233 			/* kprobes don't support file offsets */
1234 			if (ctx->flags & TPARG_FL_KERNEL) {
1235 				trace_probe_log_err(ctx->offset, FILE_ON_KPROBE);
1236 				return -EINVAL;
1237 			}
1238 			ret = kstrtol(arg + 2, 0, &offset);
1239 			if (ret) {
1240 				trace_probe_log_err(ctx->offset, BAD_FILE_OFFS);
1241 				break;
1242 			}
1243 
1244 			code->op = FETCH_OP_FOFFS;
1245 			code->immediate = (unsigned long)offset;  // imm64?
1246 			offset = 0;
1247 		} else {
1248 			/* uprobes don't support symbols */
1249 			if (!(ctx->flags & TPARG_FL_KERNEL)) {
1250 				trace_probe_log_err(ctx->offset, SYM_ON_UPROBE);
1251 				return -EINVAL;
1252 			}
1253 			/* Preserve symbol for updating */
1254 			code->op = FETCH_NOP_SYMBOL;
1255 			code->data = kstrdup(arg + 1, GFP_KERNEL);
1256 			if (!code->data)
1257 				return -ENOMEM;
1258 			if (++code == end) {
1259 				trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1260 				return -EINVAL;
1261 			}
1262 			code->op = FETCH_OP_IMM;
1263 			code->immediate = 0;
1264 		}
1265 		/* These are fetching from memory */
1266 		if (++code == end) {
1267 			trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1268 			return -EINVAL;
1269 		}
1270 		*pcode = code;
1271 		code->op = FETCH_OP_DEREF;
1272 		code->offset = offset;
1273 		break;
1274 
1275 	case '+':	/* deref memory */
1276 	case '-':
1277 		if (arg[1] == 'u') {
1278 			deref = FETCH_OP_UDEREF;
1279 			arg[1] = arg[0];
1280 			arg++;
1281 		}
1282 		if (arg[0] == '+')
1283 			arg++;	/* Skip '+', because kstrtol() rejects it. */
1284 		tmp = strchr(arg, '(');
1285 		if (!tmp) {
1286 			trace_probe_log_err(ctx->offset, DEREF_NEED_BRACE);
1287 			return -EINVAL;
1288 		}
1289 		*tmp = '\0';
1290 		ret = kstrtol(arg, 0, &offset);
1291 		if (ret) {
1292 			trace_probe_log_err(ctx->offset, BAD_DEREF_OFFS);
1293 			break;
1294 		}
1295 		ctx->offset += (tmp + 1 - arg) + (arg[0] != '-' ? 1 : 0);
1296 		arg = tmp + 1;
1297 		tmp = strrchr(arg, ')');
1298 		if (!tmp) {
1299 			trace_probe_log_err(ctx->offset + strlen(arg),
1300 					    DEREF_OPEN_BRACE);
1301 			return -EINVAL;
1302 		} else {
1303 			const struct fetch_type *t2 = find_fetch_type(NULL, ctx->flags);
1304 			int cur_offs = ctx->offset;
1305 
1306 			*tmp = '\0';
1307 			ret = parse_probe_arg(arg, t2, &code, end, ctx);
1308 			if (ret)
1309 				break;
1310 			ctx->offset = cur_offs;
1311 			if (code->op == FETCH_OP_COMM ||
1312 			    code->op == FETCH_OP_DATA) {
1313 				trace_probe_log_err(ctx->offset, COMM_CANT_DEREF);
1314 				return -EINVAL;
1315 			}
1316 			if (++code == end) {
1317 				trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1318 				return -EINVAL;
1319 			}
1320 			*pcode = code;
1321 
1322 			code->op = deref;
1323 			code->offset = offset;
1324 			/* Reset the last type if used */
1325 			ctx->last_type = NULL;
1326 		}
1327 		break;
1328 	case '\\':	/* Immediate value */
1329 		if (arg[1] == '"') {	/* Immediate string */
1330 			ret = __parse_imm_string(arg + 2, &tmp, ctx->offset + 2);
1331 			if (ret)
1332 				break;
1333 			code->op = FETCH_OP_DATA;
1334 			code->data = tmp;
1335 		} else {
1336 			ret = str_to_immediate(arg + 1, &code->immediate);
1337 			if (ret)
1338 				trace_probe_log_err(ctx->offset + 1, BAD_IMM);
1339 			else
1340 				code->op = FETCH_OP_IMM;
1341 		}
1342 		break;
1343 	case '(':
1344 		ret = handle_typecast(arg, pcode, end, ctx);
1345 		break;
1346 	default:
1347 		if (isalpha(arg[0]) || arg[0] == '_') {	/* BTF variable */
1348 			if (!tparg_is_function_entry(ctx->flags) &&
1349 			    !tparg_is_function_return(ctx->flags)) {
1350 				trace_probe_log_err(ctx->offset, NOSUP_BTFARG);
1351 				return -EINVAL;
1352 			}
1353 			ret = parse_btf_arg(arg, pcode, end, ctx);
1354 			break;
1355 		}
1356 	}
1357 	if (!ret && code->op == FETCH_OP_NOP) {
1358 		/* Parsed, but do not find fetch method */
1359 		trace_probe_log_err(ctx->offset, BAD_FETCH_ARG);
1360 		ret = -EINVAL;
1361 	}
1362 	return ret;
1363 }
1364 
1365 /* Bitfield type needs to be parsed into a fetch function */
__parse_bitfield_probe_arg(const char * bf,const struct fetch_type * t,struct fetch_insn ** pcode)1366 static int __parse_bitfield_probe_arg(const char *bf,
1367 				      const struct fetch_type *t,
1368 				      struct fetch_insn **pcode)
1369 {
1370 	struct fetch_insn *code = *pcode;
1371 	unsigned long bw, bo;
1372 	char *tail;
1373 
1374 	if (*bf != 'b')
1375 		return 0;
1376 
1377 	bw = simple_strtoul(bf + 1, &tail, 0);	/* Use simple one */
1378 
1379 	if (bw == 0 || *tail != '@')
1380 		return -EINVAL;
1381 
1382 	bf = tail + 1;
1383 	bo = simple_strtoul(bf, &tail, 0);
1384 
1385 	if (tail == bf || *tail != '/')
1386 		return -EINVAL;
1387 	code++;
1388 	if (code->op != FETCH_OP_NOP)
1389 		return -EINVAL;
1390 	*pcode = code;
1391 
1392 	code->op = FETCH_OP_MOD_BF;
1393 	code->lshift = BYTES_TO_BITS(t->size) - (bw + bo);
1394 	code->rshift = BYTES_TO_BITS(t->size) - bw;
1395 	code->basesize = t->size;
1396 
1397 	return (BYTES_TO_BITS(t->size) < (bw + bo)) ? -EINVAL : 0;
1398 }
1399 
1400 /* Split type part from @arg and return it. */
parse_probe_arg_type(char * arg,struct probe_arg * parg,struct traceprobe_parse_context * ctx)1401 static char *parse_probe_arg_type(char *arg, struct probe_arg *parg,
1402 				  struct traceprobe_parse_context *ctx)
1403 {
1404 	char *t = NULL, *t2, *t3;
1405 	int offs;
1406 
1407 	t = strchr(arg, ':');
1408 	if (t) {
1409 		*t++ = '\0';
1410 		t2 = strchr(t, '[');
1411 		if (t2) {
1412 			*t2++ = '\0';
1413 			t3 = strchr(t2, ']');
1414 			if (!t3) {
1415 				offs = t2 + strlen(t2) - arg;
1416 
1417 				trace_probe_log_err(ctx->offset + offs,
1418 						    ARRAY_NO_CLOSE);
1419 				return ERR_PTR(-EINVAL);
1420 			} else if (t3[1] != '\0') {
1421 				trace_probe_log_err(ctx->offset + t3 + 1 - arg,
1422 						    BAD_ARRAY_SUFFIX);
1423 				return ERR_PTR(-EINVAL);
1424 			}
1425 			*t3 = '\0';
1426 			if (kstrtouint(t2, 0, &parg->count) || !parg->count) {
1427 				trace_probe_log_err(ctx->offset + t2 - arg,
1428 						    BAD_ARRAY_NUM);
1429 				return ERR_PTR(-EINVAL);
1430 			}
1431 			if (parg->count > MAX_ARRAY_LEN) {
1432 				trace_probe_log_err(ctx->offset + t2 - arg,
1433 						    ARRAY_TOO_BIG);
1434 				return ERR_PTR(-EINVAL);
1435 			}
1436 		}
1437 	}
1438 	offs = t ? t - arg : 0;
1439 
1440 	/*
1441 	 * Since $comm and immediate string can not be dereferenced,
1442 	 * we can find those by strcmp. But ignore for eprobes.
1443 	 */
1444 	if (!(ctx->flags & TPARG_FL_TEVENT) &&
1445 	    (strcmp(arg, "$comm") == 0 || strcmp(arg, "$COMM") == 0 ||
1446 	     strncmp(arg, "\\\"", 2) == 0)) {
1447 		/* The type of $comm must be "string", and not an array type. */
1448 		if (parg->count || (t && strcmp(t, "string"))) {
1449 			trace_probe_log_err(ctx->offset + offs, NEED_STRING_TYPE);
1450 			return ERR_PTR(-EINVAL);
1451 		}
1452 		parg->type = find_fetch_type("string", ctx->flags);
1453 	} else
1454 		parg->type = find_fetch_type(t, ctx->flags);
1455 
1456 	if (!parg->type) {
1457 		trace_probe_log_err(ctx->offset + offs, BAD_TYPE);
1458 		return ERR_PTR(-EINVAL);
1459 	}
1460 
1461 	return t;
1462 }
1463 
1464 /* After parsing, adjust the fetch_insn according to the probe_arg */
finalize_fetch_insn(struct fetch_insn * code,struct probe_arg * parg,char * type,int type_offset,struct traceprobe_parse_context * ctx)1465 static int finalize_fetch_insn(struct fetch_insn *code,
1466 			       struct probe_arg *parg,
1467 			       char *type,
1468 			       int type_offset,
1469 			       struct traceprobe_parse_context *ctx)
1470 {
1471 	struct fetch_insn *scode;
1472 	int ret;
1473 
1474 	/* Store operation */
1475 	if (parg->type->is_string) {
1476 		/* Check bad combination of the type and the last fetch_insn. */
1477 		if (!strcmp(parg->type->name, "symstr")) {
1478 			if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK &&
1479 			    code->op != FETCH_OP_RETVAL && code->op != FETCH_OP_ARG &&
1480 			    code->op != FETCH_OP_DEREF && code->op != FETCH_OP_TP_ARG) {
1481 				trace_probe_log_err(ctx->offset + type_offset,
1482 						    BAD_SYMSTRING);
1483 				return -EINVAL;
1484 			}
1485 		} else {
1486 			if (code->op != FETCH_OP_DEREF && code->op != FETCH_OP_UDEREF &&
1487 			    code->op != FETCH_OP_IMM && code->op != FETCH_OP_COMM &&
1488 			    code->op != FETCH_OP_DATA && code->op != FETCH_OP_TP_ARG) {
1489 				trace_probe_log_err(ctx->offset + type_offset,
1490 						    BAD_STRING);
1491 				return -EINVAL;
1492 			}
1493 		}
1494 
1495 		if (!strcmp(parg->type->name, "symstr") ||
1496 		    (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM ||
1497 		     code->op == FETCH_OP_DATA) || code->op == FETCH_OP_TP_ARG ||
1498 		     parg->count) {
1499 			/*
1500 			 * IMM, DATA and COMM is pointing actual address, those
1501 			 * must be kept, and if parg->count != 0, this is an
1502 			 * array of string pointers instead of string address
1503 			 * itself.
1504 			 * For the symstr, it doesn't need to dereference, thus
1505 			 * it just get the value.
1506 			 */
1507 			code++;
1508 			if (code->op != FETCH_OP_NOP) {
1509 				trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1510 				return -EINVAL;
1511 			}
1512 		}
1513 
1514 		/* If op == DEREF, replace it with STRING */
1515 		if (!strcmp(parg->type->name, "ustring") ||
1516 		    code->op == FETCH_OP_UDEREF)
1517 			code->op = FETCH_OP_ST_USTRING;
1518 		else if (!strcmp(parg->type->name, "symstr"))
1519 			code->op = FETCH_OP_ST_SYMSTR;
1520 		else
1521 			code->op = FETCH_OP_ST_STRING;
1522 		code->size = parg->type->size;
1523 		parg->dynamic = true;
1524 	} else if (code->op == FETCH_OP_DEREF) {
1525 		code->op = FETCH_OP_ST_MEM;
1526 		code->size = parg->type->size;
1527 	} else if (code->op == FETCH_OP_UDEREF) {
1528 		code->op = FETCH_OP_ST_UMEM;
1529 		code->size = parg->type->size;
1530 	} else {
1531 		code++;
1532 		if (code->op != FETCH_OP_NOP) {
1533 			trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1534 			return -E2BIG;
1535 		}
1536 		code->op = FETCH_OP_ST_RAW;
1537 		code->size = parg->type->size;
1538 	}
1539 
1540 	/* Save storing fetch_insn. */
1541 	scode = code;
1542 
1543 	/* Modify operation */
1544 	if (type != NULL) {
1545 		/* Bitfield needs a special fetch_insn. */
1546 		ret = __parse_bitfield_probe_arg(type, parg->type, &code);
1547 		if (ret) {
1548 			trace_probe_log_err(ctx->offset + type_offset, BAD_BITFIELD);
1549 			return ret;
1550 		}
1551 	} else if (IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS) &&
1552 		   ctx->last_type) {
1553 		/* If user not specified the type, try parsing BTF bitfield. */
1554 		ret = parse_btf_bitfield(&code, ctx);
1555 		if (ret)
1556 			return ret;
1557 	}
1558 
1559 	/* Loop(Array) operation */
1560 	if (parg->count) {
1561 		if (scode->op != FETCH_OP_ST_MEM &&
1562 		    scode->op != FETCH_OP_ST_STRING &&
1563 		    scode->op != FETCH_OP_ST_USTRING) {
1564 			trace_probe_log_err(ctx->offset + type_offset, BAD_STRING);
1565 			return -EINVAL;
1566 		}
1567 		code++;
1568 		if (code->op != FETCH_OP_NOP) {
1569 			trace_probe_log_err(ctx->offset, TOO_MANY_OPS);
1570 			return -E2BIG;
1571 		}
1572 		code->op = FETCH_OP_LP_ARRAY;
1573 		code->param = parg->count;
1574 	}
1575 
1576 	/* Finalize the fetch_insn array. */
1577 	code++;
1578 	code->op = FETCH_OP_END;
1579 
1580 	return 0;
1581 }
1582 
1583 /* String length checking wrapper */
traceprobe_parse_probe_arg_body(const char * argv,ssize_t * size,struct probe_arg * parg,struct traceprobe_parse_context * ctx)1584 static int traceprobe_parse_probe_arg_body(const char *argv, ssize_t *size,
1585 					   struct probe_arg *parg,
1586 					   struct traceprobe_parse_context *ctx)
1587 {
1588 	struct fetch_insn *code, *tmp = NULL;
1589 	char *type, *arg __free(kfree) = NULL;
1590 	int ret, len;
1591 
1592 	len = strlen(argv);
1593 	if (len > MAX_ARGSTR_LEN) {
1594 		trace_probe_log_err(ctx->offset, ARG_TOO_LONG);
1595 		return -E2BIG;
1596 	} else if (len == 0) {
1597 		trace_probe_log_err(ctx->offset, NO_ARG_BODY);
1598 		return -EINVAL;
1599 	}
1600 
1601 	arg = kstrdup(argv, GFP_KERNEL);
1602 	if (!arg)
1603 		return -ENOMEM;
1604 
1605 	parg->comm = kstrdup(arg, GFP_KERNEL);
1606 	if (!parg->comm)
1607 		return -ENOMEM;
1608 
1609 	type = parse_probe_arg_type(arg, parg, ctx);
1610 	if (IS_ERR(type))
1611 		return PTR_ERR(type);
1612 
1613 	code = tmp = kzalloc_objs(*code, FETCH_INSN_MAX);
1614 	if (!code)
1615 		return -ENOMEM;
1616 	code[FETCH_INSN_MAX - 1].op = FETCH_OP_END;
1617 
1618 	ctx->last_type = NULL;
1619 	ret = parse_probe_arg(arg, parg->type, &code, &code[FETCH_INSN_MAX - 1],
1620 			      ctx);
1621 	if (ret < 0)
1622 		goto fail;
1623 
1624 	/* Update storing type if BTF is available */
1625 	if (IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS) &&
1626 	    ctx->last_type) {
1627 		if (!type) {
1628 			parg->type = find_fetch_type_from_btf_type(ctx);
1629 		} else if (strstr(type, "string")) {
1630 			ret = check_prepare_btf_string_fetch(type, &code, ctx);
1631 			if (ret)
1632 				goto fail;
1633 		}
1634 	}
1635 	parg->offset = *size;
1636 	*size += parg->type->size * (parg->count ?: 1);
1637 
1638 	if (*size > MAX_PROBE_EVENT_SIZE) {
1639 		ret = -E2BIG;
1640 		trace_probe_log_err(ctx->offset, EVENT_TOO_BIG);
1641 		goto fail;
1642 	}
1643 
1644 	if (parg->count) {
1645 		len = strlen(parg->type->fmttype) + 6;
1646 		parg->fmt = kmalloc(len, GFP_KERNEL);
1647 		if (!parg->fmt) {
1648 			ret = -ENOMEM;
1649 			goto fail;
1650 		}
1651 		snprintf(parg->fmt, len, "%s[%d]", parg->type->fmttype,
1652 			 parg->count);
1653 	}
1654 
1655 	ret = finalize_fetch_insn(code, parg, type, type ? type - arg : 0, ctx);
1656 	if (ret < 0)
1657 		goto fail;
1658 
1659 	for (; code < tmp + FETCH_INSN_MAX; code++)
1660 		if (code->op == FETCH_OP_END)
1661 			break;
1662 	/* Shrink down the code buffer */
1663 	parg->code = kzalloc_objs(*code, code - tmp + 1);
1664 	if (!parg->code)
1665 		ret = -ENOMEM;
1666 	else
1667 		memcpy(parg->code, tmp, sizeof(*code) * (code - tmp + 1));
1668 
1669 fail:
1670 	if (ret < 0) {
1671 		for (code = tmp; code < tmp + FETCH_INSN_MAX; code++)
1672 			if (code->op == FETCH_NOP_SYMBOL ||
1673 			    code->op == FETCH_OP_DATA)
1674 				kfree(code->data);
1675 	}
1676 	kfree(tmp);
1677 
1678 	/* struct_btf should not be passed to other arguments */
1679 	clear_struct_btf(ctx);
1680 
1681 	return ret;
1682 }
1683 
1684 /* Return 1 if name is reserved or already used by another argument */
traceprobe_conflict_field_name(const char * name,struct probe_arg * args,int narg)1685 static int traceprobe_conflict_field_name(const char *name,
1686 					  struct probe_arg *args, int narg)
1687 {
1688 	int i;
1689 
1690 	for (i = 0; i < ARRAY_SIZE(reserved_field_names); i++)
1691 		if (strcmp(reserved_field_names[i], name) == 0)
1692 			return 1;
1693 
1694 	for (i = 0; i < narg; i++)
1695 		if (strcmp(args[i].name, name) == 0)
1696 			return 1;
1697 
1698 	return 0;
1699 }
1700 
generate_probe_arg_name(const char * arg,int idx)1701 static char *generate_probe_arg_name(const char *arg, int idx)
1702 {
1703 	char *name = NULL;
1704 	const char *end;
1705 
1706 	/*
1707 	 * If argument name is omitted, try arg as a name (BTF variable)
1708 	 * or "argN".
1709 	 */
1710 	if (IS_ENABLED(CONFIG_PROBE_EVENTS_BTF_ARGS)) {
1711 		end = strchr(arg, ':');
1712 		if (!end)
1713 			end = arg + strlen(arg);
1714 
1715 		name = kmemdup_nul(arg, end - arg, GFP_KERNEL);
1716 		if (!name || !is_good_name(name)) {
1717 			kfree(name);
1718 			name = NULL;
1719 		}
1720 	}
1721 
1722 	if (!name)
1723 		name = kasprintf(GFP_KERNEL, "arg%d", idx + 1);
1724 
1725 	return name;
1726 }
1727 
traceprobe_parse_probe_arg(struct trace_probe * tp,int i,const char * arg,struct traceprobe_parse_context * ctx)1728 int traceprobe_parse_probe_arg(struct trace_probe *tp, int i, const char *arg,
1729 			       struct traceprobe_parse_context *ctx)
1730 {
1731 	struct probe_arg *parg = &tp->args[i];
1732 	const char *body;
1733 
1734 	ctx->tp = tp;
1735 	body = strchr(arg, '=');
1736 	if (body) {
1737 		if (body - arg > MAX_ARG_NAME_LEN) {
1738 			trace_probe_log_err(0, ARG_NAME_TOO_LONG);
1739 			return -EINVAL;
1740 		} else if (body == arg) {
1741 			trace_probe_log_err(0, NO_ARG_NAME);
1742 			return -EINVAL;
1743 		}
1744 		parg->name = kmemdup_nul(arg, body - arg, GFP_KERNEL);
1745 		body++;
1746 	} else {
1747 		parg->name = generate_probe_arg_name(arg, i);
1748 		body = arg;
1749 	}
1750 	if (!parg->name)
1751 		return -ENOMEM;
1752 
1753 	if (!is_good_name(parg->name)) {
1754 		trace_probe_log_err(0, BAD_ARG_NAME);
1755 		return -EINVAL;
1756 	}
1757 	if (traceprobe_conflict_field_name(parg->name, tp->args, i)) {
1758 		trace_probe_log_err(0, USED_ARG_NAME);
1759 		return -EINVAL;
1760 	}
1761 	ctx->offset = body - arg;
1762 	/* Parse fetch argument */
1763 	return traceprobe_parse_probe_arg_body(body, &tp->size, parg, ctx);
1764 }
1765 
traceprobe_free_probe_arg(struct probe_arg * arg)1766 void traceprobe_free_probe_arg(struct probe_arg *arg)
1767 {
1768 	struct fetch_insn *code = arg->code;
1769 
1770 	while (code && code->op != FETCH_OP_END) {
1771 		if (code->op == FETCH_NOP_SYMBOL ||
1772 		    code->op == FETCH_OP_DATA)
1773 			kfree(code->data);
1774 		code++;
1775 	}
1776 	kfree(arg->code);
1777 	kfree(arg->name);
1778 	kfree(arg->comm);
1779 	kfree(arg->fmt);
1780 }
1781 
argv_has_var_arg(int argc,const char * argv[],int * args_idx,struct traceprobe_parse_context * ctx)1782 static int argv_has_var_arg(int argc, const char *argv[], int *args_idx,
1783 			    struct traceprobe_parse_context *ctx)
1784 {
1785 	int i, found = 0;
1786 
1787 	for (i = 0; i < argc; i++)
1788 		if (str_has_prefix(argv[i], "$arg")) {
1789 			trace_probe_log_set_index(i + 2);
1790 
1791 			if (!tparg_is_function_entry(ctx->flags) &&
1792 			    !tparg_is_function_return(ctx->flags)) {
1793 				trace_probe_log_err(0, NOFENTRY_ARGS);
1794 				return -EINVAL;
1795 			}
1796 
1797 			if (isdigit(argv[i][4])) {
1798 				found = 1;
1799 				continue;
1800 			}
1801 
1802 			if (argv[i][4] != '*') {
1803 				trace_probe_log_err(0, BAD_VAR);
1804 				return -EINVAL;
1805 			}
1806 
1807 			if (*args_idx >= 0 && *args_idx < argc) {
1808 				trace_probe_log_err(0, DOUBLE_ARGS);
1809 				return -EINVAL;
1810 			}
1811 			found = 1;
1812 			*args_idx = i;
1813 		}
1814 
1815 	return found;
1816 }
1817 
sprint_nth_btf_arg(int idx,const char * type,char * buf,int bufsize,struct traceprobe_parse_context * ctx)1818 static int sprint_nth_btf_arg(int idx, const char *type,
1819 			      char *buf, int bufsize,
1820 			      struct traceprobe_parse_context *ctx)
1821 {
1822 	const char *name;
1823 	int ret;
1824 
1825 	if (idx >= ctx->nr_params) {
1826 		trace_probe_log_err(0, NO_BTFARG);
1827 		return -ENOENT;
1828 	}
1829 	name = btf_name_by_offset(ctx->btf, ctx->params[idx].name_off);
1830 	if (!name) {
1831 		trace_probe_log_err(0, NO_BTF_ENTRY);
1832 		return -ENOENT;
1833 	}
1834 	ret = snprintf(buf, bufsize, "%s%s", name, type);
1835 	if (ret >= bufsize) {
1836 		trace_probe_log_err(0, ARGS_2LONG);
1837 		return -E2BIG;
1838 	}
1839 	return ret;
1840 }
1841 
1842 /* Return new_argv which must be freed after use */
traceprobe_expand_meta_args(int argc,const char * argv[],int * new_argc,char * buf,int bufsize,struct traceprobe_parse_context * ctx)1843 const char **traceprobe_expand_meta_args(int argc, const char *argv[],
1844 					 int *new_argc, char *buf, int bufsize,
1845 					 struct traceprobe_parse_context *ctx)
1846 {
1847 	const struct btf_param *params = NULL;
1848 	int i, j, n, used, ret, args_idx = -1;
1849 	const char **new_argv __free(kfree) = NULL;
1850 
1851 	ret = argv_has_var_arg(argc, argv, &args_idx, ctx);
1852 	if (ret < 0)
1853 		return ERR_PTR(ret);
1854 
1855 	if (!ret) {
1856 		*new_argc = argc;
1857 		return NULL;
1858 	}
1859 
1860 	ret = query_btf_context(ctx);
1861 	if (ret < 0 || ctx->nr_params == 0) {
1862 		if (args_idx != -1) {
1863 			/* $arg* requires BTF info */
1864 			trace_probe_log_err(0, NOSUP_BTFARG);
1865 			return (const char **)params;
1866 		}
1867 		*new_argc = argc;
1868 		return NULL;
1869 	}
1870 
1871 	if (args_idx >= 0)
1872 		*new_argc = argc + ctx->nr_params - 1;
1873 	else
1874 		*new_argc = argc;
1875 
1876 	new_argv = kcalloc(*new_argc, sizeof(char *), GFP_KERNEL);
1877 	if (!new_argv)
1878 		return ERR_PTR(-ENOMEM);
1879 
1880 	used = 0;
1881 	for (i = 0, j = 0; i < argc; i++) {
1882 		trace_probe_log_set_index(i + 2);
1883 		if (i == args_idx) {
1884 			for (n = 0; n < ctx->nr_params; n++) {
1885 				ret = sprint_nth_btf_arg(n, "", buf + used,
1886 							 bufsize - used, ctx);
1887 				if (ret < 0)
1888 					return ERR_PTR(ret);
1889 
1890 				new_argv[j++] = buf + used;
1891 				used += ret + 1;
1892 			}
1893 			continue;
1894 		}
1895 
1896 		if (str_has_prefix(argv[i], "$arg")) {
1897 			char *type = NULL;
1898 
1899 			n = simple_strtoul(argv[i] + 4, &type, 10);
1900 			if (type && !(*type == ':' || *type == '\0')) {
1901 				trace_probe_log_err(0, BAD_VAR);
1902 				return ERR_PTR(-ENOENT);
1903 			}
1904 			/* Note: $argN starts from $arg1 */
1905 			ret = sprint_nth_btf_arg(n - 1, type, buf + used,
1906 						 bufsize - used, ctx);
1907 			if (ret < 0)
1908 				return ERR_PTR(ret);
1909 			new_argv[j++] = buf + used;
1910 			used += ret + 1;
1911 		} else
1912 			new_argv[j++] = argv[i];
1913 	}
1914 
1915 	return_ptr(new_argv);
1916 }
1917 
1918 /* @buf: *buf must be equal to NULL. Caller must to free *buf */
traceprobe_expand_dentry_args(int argc,const char * argv[],char ** buf)1919 int traceprobe_expand_dentry_args(int argc, const char *argv[], char **buf)
1920 {
1921 	int i, used, ret;
1922 	const int bufsize = MAX_DENTRY_ARGS_LEN;
1923 	char *tmpbuf __free(kfree) = NULL;
1924 
1925 	if (*buf)
1926 		return -EINVAL;
1927 
1928 	used = 0;
1929 	for (i = 0; i < argc; i++) {
1930 		char *tmp __free(kfree) = NULL;
1931 		char *equal;
1932 		size_t arg_len;
1933 
1934 		if (!glob_match("*:%p[dD]", argv[i]))
1935 			continue;
1936 
1937 		if (!tmpbuf) {
1938 			tmpbuf = kmalloc(bufsize, GFP_KERNEL);
1939 			if (!tmpbuf)
1940 				return -ENOMEM;
1941 		}
1942 
1943 		tmp = kstrdup(argv[i], GFP_KERNEL);
1944 		if (!tmp)
1945 			return -ENOMEM;
1946 
1947 		equal = strchr(tmp, '=');
1948 		if (equal)
1949 			*equal = '\0';
1950 		arg_len = strlen(argv[i]);
1951 		tmp[arg_len - 4] = '\0';
1952 		if (argv[i][arg_len - 1] == 'd')
1953 			ret = snprintf(tmpbuf + used, bufsize - used,
1954 				       "%s%s+0x0(+0x%zx(%s)):string",
1955 				       equal ? tmp : "", equal ? "=" : "",
1956 				       offsetof(struct dentry, d_name.name),
1957 				       equal ? equal + 1 : tmp);
1958 		else
1959 			ret = snprintf(tmpbuf + used, bufsize - used,
1960 				       "%s%s+0x0(+0x%zx(+0x%zx(%s))):string",
1961 				       equal ? tmp : "", equal ? "=" : "",
1962 				       offsetof(struct dentry, d_name.name),
1963 				       offsetof(struct file, f_path.dentry),
1964 				       equal ? equal + 1 : tmp);
1965 
1966 		if (ret >= bufsize - used)
1967 			return -ENOMEM;
1968 		argv[i] = tmpbuf + used;
1969 		used += ret + 1;
1970 	}
1971 
1972 	*buf = no_free_ptr(tmpbuf);
1973 	return 0;
1974 }
1975 
traceprobe_finish_parse(struct traceprobe_parse_context * ctx)1976 void traceprobe_finish_parse(struct traceprobe_parse_context *ctx)
1977 {
1978 	clear_btf_context(ctx);
1979 }
1980 
traceprobe_update_arg(struct probe_arg * arg)1981 int traceprobe_update_arg(struct probe_arg *arg)
1982 {
1983 	struct fetch_insn *code = arg->code;
1984 	long offset;
1985 	char *tmp;
1986 	char c;
1987 	int ret = 0;
1988 
1989 	while (code && code->op != FETCH_OP_END) {
1990 		if (code->op == FETCH_NOP_SYMBOL) {
1991 			if (code[1].op != FETCH_OP_IMM)
1992 				return -EINVAL;
1993 
1994 			tmp = strpbrk(code->data, "+-");
1995 			if (tmp)
1996 				c = *tmp;
1997 			ret = traceprobe_split_symbol_offset(code->data,
1998 							     &offset);
1999 			if (ret)
2000 				return ret;
2001 
2002 			code[1].immediate =
2003 				(unsigned long)kallsyms_lookup_name(code->data);
2004 			if (tmp)
2005 				*tmp = c;
2006 			if (!code[1].immediate)
2007 				return -ENOENT;
2008 			code[1].immediate += offset;
2009 		}
2010 		code++;
2011 	}
2012 	return 0;
2013 }
2014 
2015 /* When len=0, we just calculate the needed length */
2016 #define LEN_OR_ZERO (len ? len - pos : 0)
__set_print_fmt(struct trace_probe * tp,char * buf,int len,enum probe_print_type ptype)2017 static int __set_print_fmt(struct trace_probe *tp, char *buf, int len,
2018 			   enum probe_print_type ptype)
2019 {
2020 	struct probe_arg *parg;
2021 	int i, j;
2022 	int pos = 0;
2023 	const char *fmt, *arg;
2024 
2025 	switch (ptype) {
2026 	case PROBE_PRINT_NORMAL:
2027 		fmt = "(%lx)";
2028 		arg = ", REC->" FIELD_STRING_IP;
2029 		break;
2030 	case PROBE_PRINT_RETURN:
2031 		fmt = "(%lx <- %lx)";
2032 		arg = ", REC->" FIELD_STRING_FUNC ", REC->" FIELD_STRING_RETIP;
2033 		break;
2034 	case PROBE_PRINT_EVENT:
2035 		fmt = "";
2036 		arg = "";
2037 		break;
2038 	default:
2039 		WARN_ON_ONCE(1);
2040 		return 0;
2041 	}
2042 
2043 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"%s", fmt);
2044 
2045 	for (i = 0; i < tp->nr_args; i++) {
2046 		parg = tp->args + i;
2047 		pos += snprintf(buf + pos, LEN_OR_ZERO, " %s=", parg->name);
2048 		if (parg->count) {
2049 			pos += snprintf(buf + pos, LEN_OR_ZERO, "{%s",
2050 					parg->type->fmt);
2051 			for (j = 1; j < parg->count; j++)
2052 				pos += snprintf(buf + pos, LEN_OR_ZERO, ",%s",
2053 						parg->type->fmt);
2054 			pos += snprintf(buf + pos, LEN_OR_ZERO, "}");
2055 		} else
2056 			pos += snprintf(buf + pos, LEN_OR_ZERO, "%s",
2057 					parg->type->fmt);
2058 	}
2059 
2060 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"%s", arg);
2061 
2062 	for (i = 0; i < tp->nr_args; i++) {
2063 		parg = tp->args + i;
2064 		if (parg->count) {
2065 			if (parg->type->is_string)
2066 				fmt = ", __get_str(%s[%d])";
2067 			else
2068 				fmt = ", REC->%s[%d]";
2069 			for (j = 0; j < parg->count; j++)
2070 				pos += snprintf(buf + pos, LEN_OR_ZERO,
2071 						fmt, parg->name, j);
2072 		} else {
2073 			if (parg->type->is_string)
2074 				fmt = ", __get_str(%s)";
2075 			else
2076 				fmt = ", REC->%s";
2077 			pos += snprintf(buf + pos, LEN_OR_ZERO,
2078 					fmt, parg->name);
2079 		}
2080 	}
2081 
2082 	/* return the length of print_fmt */
2083 	return pos;
2084 }
2085 #undef LEN_OR_ZERO
2086 
traceprobe_set_print_fmt(struct trace_probe * tp,enum probe_print_type ptype)2087 int traceprobe_set_print_fmt(struct trace_probe *tp, enum probe_print_type ptype)
2088 {
2089 	struct trace_event_call *call = trace_probe_event_call(tp);
2090 	int len;
2091 	char *print_fmt;
2092 
2093 	/* First: called with 0 length to calculate the needed length */
2094 	len = __set_print_fmt(tp, NULL, 0, ptype);
2095 	print_fmt = kmalloc(len + 1, GFP_KERNEL);
2096 	if (!print_fmt)
2097 		return -ENOMEM;
2098 
2099 	/* Second: actually write the @print_fmt */
2100 	__set_print_fmt(tp, print_fmt, len + 1, ptype);
2101 	call->print_fmt = print_fmt;
2102 
2103 	return 0;
2104 }
2105 
traceprobe_define_arg_fields(struct trace_event_call * event_call,size_t offset,struct trace_probe * tp)2106 int traceprobe_define_arg_fields(struct trace_event_call *event_call,
2107 				 size_t offset, struct trace_probe *tp)
2108 {
2109 	int ret, i;
2110 
2111 	/* Set argument names as fields */
2112 	for (i = 0; i < tp->nr_args; i++) {
2113 		struct probe_arg *parg = &tp->args[i];
2114 		const char *fmt = parg->type->fmttype;
2115 		int size = parg->type->size;
2116 
2117 		if (parg->fmt)
2118 			fmt = parg->fmt;
2119 		if (parg->count)
2120 			size *= parg->count;
2121 		ret = trace_define_field(event_call, fmt, parg->name,
2122 					 offset + parg->offset, size,
2123 					 parg->type->is_signed,
2124 					 FILTER_OTHER);
2125 		if (ret)
2126 			return ret;
2127 	}
2128 	return 0;
2129 }
2130 
trace_probe_event_free(struct trace_probe_event * tpe)2131 static void trace_probe_event_free(struct trace_probe_event *tpe)
2132 {
2133 	kfree(tpe->class.system);
2134 	kfree(tpe->call.name);
2135 	kfree(tpe->call.print_fmt);
2136 	kfree(tpe);
2137 }
2138 
trace_probe_append(struct trace_probe * tp,struct trace_probe * to)2139 int trace_probe_append(struct trace_probe *tp, struct trace_probe *to)
2140 {
2141 	if (trace_probe_has_sibling(tp))
2142 		return -EBUSY;
2143 
2144 	list_del_init(&tp->list);
2145 	trace_probe_event_free(tp->event);
2146 
2147 	tp->event = to->event;
2148 	list_add_tail(&tp->list, trace_probe_probe_list(to));
2149 
2150 	return 0;
2151 }
2152 
trace_probe_unlink(struct trace_probe * tp)2153 void trace_probe_unlink(struct trace_probe *tp)
2154 {
2155 	list_del_init(&tp->list);
2156 	if (list_empty(trace_probe_probe_list(tp)))
2157 		trace_probe_event_free(tp->event);
2158 	tp->event = NULL;
2159 }
2160 
trace_probe_cleanup(struct trace_probe * tp)2161 void trace_probe_cleanup(struct trace_probe *tp)
2162 {
2163 	int i;
2164 
2165 	for (i = 0; i < tp->nr_args; i++)
2166 		traceprobe_free_probe_arg(&tp->args[i]);
2167 
2168 	if (tp->entry_arg) {
2169 		kfree(tp->entry_arg);
2170 		tp->entry_arg = NULL;
2171 	}
2172 
2173 	if (tp->event)
2174 		trace_probe_unlink(tp);
2175 }
2176 
trace_probe_init(struct trace_probe * tp,const char * event,const char * group,bool alloc_filter,int nargs)2177 int trace_probe_init(struct trace_probe *tp, const char *event,
2178 		     const char *group, bool alloc_filter, int nargs)
2179 {
2180 	struct trace_event_call *call;
2181 	size_t size = sizeof(struct trace_probe_event);
2182 	int ret = 0;
2183 
2184 	if (!event || !group)
2185 		return -EINVAL;
2186 
2187 	if (alloc_filter)
2188 		size += sizeof(struct trace_uprobe_filter);
2189 
2190 	tp->event = kzalloc(size, GFP_KERNEL);
2191 	if (!tp->event)
2192 		return -ENOMEM;
2193 
2194 	INIT_LIST_HEAD(&tp->event->files);
2195 	INIT_LIST_HEAD(&tp->event->class.fields);
2196 	INIT_LIST_HEAD(&tp->event->probes);
2197 	INIT_LIST_HEAD(&tp->list);
2198 	list_add(&tp->list, &tp->event->probes);
2199 
2200 	call = trace_probe_event_call(tp);
2201 	call->class = &tp->event->class;
2202 	call->name = kstrdup(event, GFP_KERNEL);
2203 	if (!call->name) {
2204 		ret = -ENOMEM;
2205 		goto error;
2206 	}
2207 
2208 	tp->event->class.system = kstrdup(group, GFP_KERNEL);
2209 	if (!tp->event->class.system) {
2210 		ret = -ENOMEM;
2211 		goto error;
2212 	}
2213 
2214 	tp->nr_args = nargs;
2215 	/* Make sure pointers in args[] are NULL */
2216 	if (nargs)
2217 		memset(tp->args, 0, sizeof(tp->args[0]) * nargs);
2218 
2219 	return 0;
2220 
2221 error:
2222 	trace_probe_cleanup(tp);
2223 	return ret;
2224 }
2225 
2226 static struct trace_event_call *
find_trace_event_call(const char * system,const char * event_name)2227 find_trace_event_call(const char *system, const char *event_name)
2228 {
2229 	struct trace_event_call *tp_event;
2230 	const char *name;
2231 
2232 	list_for_each_entry(tp_event, &ftrace_events, list) {
2233 		if (!tp_event->class->system ||
2234 		    strcmp(system, tp_event->class->system))
2235 			continue;
2236 		name = trace_event_name(tp_event);
2237 		if (!name || strcmp(event_name, name))
2238 			continue;
2239 		return tp_event;
2240 	}
2241 
2242 	return NULL;
2243 }
2244 
trace_probe_register_event_call(struct trace_probe * tp)2245 int trace_probe_register_event_call(struct trace_probe *tp)
2246 {
2247 	struct trace_event_call *call = trace_probe_event_call(tp);
2248 	int ret;
2249 
2250 	lockdep_assert_held(&event_mutex);
2251 
2252 	if (find_trace_event_call(trace_probe_group_name(tp),
2253 				  trace_probe_name(tp)))
2254 		return -EEXIST;
2255 
2256 	ret = register_trace_event(&call->event);
2257 	if (!ret)
2258 		return -ENODEV;
2259 
2260 	ret = trace_add_event_call(call);
2261 	if (ret)
2262 		unregister_trace_event(&call->event);
2263 
2264 	return ret;
2265 }
2266 
trace_probe_add_file(struct trace_probe * tp,struct trace_event_file * file)2267 int trace_probe_add_file(struct trace_probe *tp, struct trace_event_file *file)
2268 {
2269 	struct event_file_link *link;
2270 
2271 	link = kmalloc_obj(*link);
2272 	if (!link)
2273 		return -ENOMEM;
2274 
2275 	link->file = file;
2276 	INIT_LIST_HEAD(&link->list);
2277 	list_add_tail_rcu(&link->list, &tp->event->files);
2278 	trace_probe_set_flag(tp, TP_FLAG_TRACE);
2279 	return 0;
2280 }
2281 
trace_probe_get_file_link(struct trace_probe * tp,struct trace_event_file * file)2282 struct event_file_link *trace_probe_get_file_link(struct trace_probe *tp,
2283 						  struct trace_event_file *file)
2284 {
2285 	struct event_file_link *link;
2286 
2287 	trace_probe_for_each_link(link, tp) {
2288 		if (link->file == file)
2289 			return link;
2290 	}
2291 
2292 	return NULL;
2293 }
2294 
trace_probe_remove_file(struct trace_probe * tp,struct trace_event_file * file)2295 int trace_probe_remove_file(struct trace_probe *tp,
2296 			    struct trace_event_file *file)
2297 {
2298 	struct event_file_link *link;
2299 
2300 	link = trace_probe_get_file_link(tp, file);
2301 	if (!link)
2302 		return -ENOENT;
2303 
2304 	list_del_rcu(&link->list);
2305 	kvfree_rcu_mightsleep(link);
2306 
2307 	if (list_empty(&tp->event->files))
2308 		trace_probe_clear_flag(tp, TP_FLAG_TRACE);
2309 
2310 	return 0;
2311 }
2312 
2313 /*
2314  * Return the smallest index of different type argument (start from 1).
2315  * If all argument types and name are same, return 0.
2316  */
trace_probe_compare_arg_type(struct trace_probe * a,struct trace_probe * b)2317 int trace_probe_compare_arg_type(struct trace_probe *a, struct trace_probe *b)
2318 {
2319 	int i;
2320 
2321 	/* In case of more arguments */
2322 	if (a->nr_args < b->nr_args)
2323 		return a->nr_args + 1;
2324 	if (a->nr_args > b->nr_args)
2325 		return b->nr_args + 1;
2326 
2327 	for (i = 0; i < a->nr_args; i++) {
2328 		if ((b->nr_args <= i) ||
2329 		    ((a->args[i].type != b->args[i].type) ||
2330 		     (a->args[i].count != b->args[i].count) ||
2331 		     strcmp(a->args[i].name, b->args[i].name)))
2332 			return i + 1;
2333 	}
2334 
2335 	return 0;
2336 }
2337 
trace_probe_match_command_args(struct trace_probe * tp,int argc,const char ** argv)2338 bool trace_probe_match_command_args(struct trace_probe *tp,
2339 				    int argc, const char **argv)
2340 {
2341 	char buf[MAX_ARGSTR_LEN + 1];
2342 	int i;
2343 
2344 	if (tp->nr_args < argc)
2345 		return false;
2346 
2347 	for (i = 0; i < argc; i++) {
2348 		snprintf(buf, sizeof(buf), "%s=%s",
2349 			 tp->args[i].name, tp->args[i].comm);
2350 		if (strcmp(buf, argv[i]))
2351 			return false;
2352 	}
2353 	return true;
2354 }
2355 
trace_probe_create(const char * raw_command,int (* createfn)(int,const char **))2356 int trace_probe_create(const char *raw_command, int (*createfn)(int, const char **))
2357 {
2358 	int argc = 0, ret = 0;
2359 	char **argv;
2360 
2361 	argv = argv_split(GFP_KERNEL, raw_command, &argc);
2362 	if (!argv)
2363 		return -ENOMEM;
2364 
2365 	if (argc)
2366 		ret = createfn(argc, (const char **)argv);
2367 
2368 	argv_free(argv);
2369 
2370 	return ret;
2371 }
2372 
trace_probe_print_args(struct trace_seq * s,struct probe_arg * args,int nr_args,u8 * data,void * field)2373 int trace_probe_print_args(struct trace_seq *s, struct probe_arg *args, int nr_args,
2374 		 u8 *data, void *field)
2375 {
2376 	void *p;
2377 	int i, j;
2378 
2379 	for (i = 0; i < nr_args; i++) {
2380 		struct probe_arg *a = args + i;
2381 
2382 		trace_seq_printf(s, " %s=", a->name);
2383 		if (likely(!a->count)) {
2384 			if (!a->type->print(s, data + a->offset, field))
2385 				return -ENOMEM;
2386 			continue;
2387 		}
2388 		trace_seq_putc(s, '{');
2389 		p = data + a->offset;
2390 		for (j = 0; j < a->count; j++) {
2391 			if (!a->type->print(s, p, field))
2392 				return -ENOMEM;
2393 			trace_seq_putc(s, j == a->count - 1 ? '}' : ',');
2394 			p += a->type->size;
2395 		}
2396 	}
2397 	return 0;
2398 }
2399