smatch.h: include scope.h
[smatch.git] / smatch_common_functions.c
blob5d5c8e7cc4075b64ad935cd7e641b324e5765312
1 /*
2 * smatch/smatch_common_functions.c
4 * Copyright (C) 2013 Oracle.
6 * Licensed under the Open Software License version 1.1
8 */
10 #include "scope.h"
11 #include "smatch.h"
12 #include "smatch_extra.h"
14 static int match_strlen(struct expression *call, void *unused, struct range_list **rl)
16 struct expression *str;
17 unsigned long max;
19 str = get_argument_from_call_expr(call->args, 0);
20 if (get_implied_strlen(str, rl) && sval_is_positive(rl_min(*rl))) {
21 *rl = cast_rl(&ulong_ctype, *rl);
22 return 1;
24 /* smatch_strlen.c is not very complete */
25 max = get_array_size_bytes_max(str);
26 if (max == 0) {
27 *rl = alloc_whole_rl(&ulong_ctype);
28 } else {
29 max--;
30 *rl = alloc_rl(ll_to_sval(0), ll_to_sval(max));
32 return 1;
35 static int match_strnlen(struct expression *call, void *unused, struct range_list **rl)
37 struct expression *limit;
38 sval_t fixed;
39 sval_t bound;
40 sval_t ulong_max = sval_type_val(&ulong_ctype, ULONG_MAX);
42 match_strlen(call, NULL, rl);
43 limit = get_argument_from_call_expr(call->args, 1);
44 if (!get_implied_max(limit, &bound))
45 return 1;
46 if (sval_cmp(bound, ulong_max) == 0)
47 return 1;
48 if (rl_to_sval(*rl, &fixed) && sval_cmp(fixed, bound) >= 0) {
49 *rl = alloc_rl(bound, bound);
50 return 1;
53 bound.value++;
54 *rl = remove_range(*rl, bound, ulong_max);
56 return 1;
59 static int match_sprintf(struct expression *call, void *_arg, struct range_list **rl)
61 int str_arg = PTR_INT(_arg);
62 int size;
64 size = get_formatted_string_size(call, str_arg);
65 if (size <= 0) {
66 *rl = alloc_whole_rl(&ulong_ctype);
67 } else {
68 /* FIXME: This is bogus. get_formatted_string_size() should be
69 returning a range_list. Also it should not add the NUL. */
70 size--;
71 *rl = alloc_rl(ll_to_sval(0), ll_to_sval(size));
73 return 1;
76 void register_common_functions(int id)
79 * When you add a new function here, then don't forget to delete it from
80 * the database and smatch_data/.
82 add_implied_return_hook("strlen", &match_strlen, NULL);
83 add_implied_return_hook("strnlen", &match_strnlen, NULL);
84 add_implied_return_hook("sprintf", &match_sprintf, INT_PTR(1));
85 add_implied_return_hook("snprintf", &match_sprintf, INT_PTR(2));