checking_for_null_instead_of_err_ptr: use smatch_kernel_err_ptr.c
[smatch/bkmgit.git] / smatch_db.c
blob45fe75d1390a9da8e807422cd1a94e3cad6884fe
1 /*
2 * Copyright (C) 2010 Dan Carpenter.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see http://www.gnu.org/copyleft/gpl.txt
18 #include <string.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <ctype.h>
22 #include "smatch.h"
23 #include "smatch_slist.h"
24 #include "smatch_extra.h"
26 struct sqlite3 *smatch_db;
27 struct sqlite3 *mem_db;
28 struct sqlite3 *cache_db;
30 int debug_db;
32 STATE(incomplete);
33 static int my_id;
35 static int return_id;
37 static void call_return_state_hooks(struct expression *expr);
38 static void call_return_states_callbacks(const char *return_ranges, struct expression *expr);
40 #define SQLITE_CACHE_PAGES 1000
42 struct def_callback {
43 int hook_type;
44 void (*callback)(const char *name, struct symbol *sym, char *key, char *value);
46 ALLOCATOR(def_callback, "definition db hook callbacks");
47 DECLARE_PTR_LIST(callback_list, struct def_callback);
48 static struct callback_list *select_caller_info_callbacks;
50 struct def_name_sym_callback {
51 int hook_type;
52 void (*callback)(const char *name, struct symbol *sym, char *value);
54 ALLOCATOR(def_name_sym_callback, "definition db hook callbacks");
55 DECLARE_PTR_LIST(name_sym_callback_list, struct def_name_sym_callback);
56 static struct name_sym_callback_list *select_caller_name_sym_callbacks;
58 struct member_info_callback {
59 int owner;
60 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm);
62 ALLOCATOR(member_info_callback, "caller_info callbacks");
63 DECLARE_PTR_LIST(member_info_cb_list, struct member_info_callback);
64 static struct member_info_cb_list *member_callbacks;
65 static struct member_info_cb_list *member_callbacks_new;
67 struct return_info_callback {
68 int owner;
69 void (*callback)(int return_id, char *return_ranges,
70 struct expression *returned_expr,
71 int param,
72 const char *printed_name,
73 struct sm_state *sm);
75 ALLOCATOR(return_info_callback, "return_info callbacks");
76 DECLARE_PTR_LIST(return_info_cb_list, struct return_info_callback);
77 static struct return_info_cb_list *return_callbacks;
79 struct returned_state_callback {
80 void (*callback)(int return_id, char *return_ranges, struct expression *return_expr);
82 ALLOCATOR(returned_state_callback, "returned state callbacks");
83 DECLARE_PTR_LIST(returned_state_cb_list, struct returned_state_callback);
84 static struct returned_state_cb_list *returned_state_callbacks;
86 struct returned_member_callback {
87 int owner;
88 void (*callback)(int return_id, char *return_ranges, struct expression *expr, char *printed_name, struct smatch_state *state);
90 ALLOCATOR(returned_member_callback, "returned member callbacks");
91 DECLARE_PTR_LIST(returned_member_cb_list, struct returned_member_callback);
92 static struct returned_member_cb_list *returned_member_callbacks;
94 struct db_implies_callback {
95 int type;
96 void (*callback)(struct expression *call, struct expression *arg, char *key, char *value);
98 ALLOCATOR(db_implies_callback, "return_implies callbacks");
99 DECLARE_PTR_LIST(db_implies_cb_list, struct db_implies_callback);
100 static struct db_implies_cb_list *return_implies_cb_list_early;
101 static struct db_implies_cb_list *return_implies_cb_list_late;
102 static struct db_implies_cb_list *call_implies_cb_list;
104 DECLARE_PTR_LIST(delete_list, delete_hook);
105 static struct delete_list *delete_hooks;
107 struct split_data {
108 const char *func, *rl;
110 static struct split_data **forced_splits;
111 static int split_count;
113 /* silently truncates if needed. */
114 char *escape_newlines(const char *str)
116 char buf[1024] = "";
117 bool found = false;
118 int i, j;
120 for (i = 0, j = 0; str[i] != '\0' && j != sizeof(buf); i++, j++) {
121 if (str[i] != '\r' && str[i] != '\n') {
122 buf[j] = str[i];
123 continue;
126 found = true;
127 buf[j++] = '\\';
128 if (j == sizeof(buf))
129 break;
130 buf[j] = 'n';
133 if (!found)
134 return alloc_sname(str);
136 if (j == sizeof(buf))
137 buf[j - 1] = '\0';
138 return alloc_sname(buf);
141 static int print_sql_output(void *unused, int argc, char **argv, char **azColName)
143 int i;
145 for (i = 0; i < argc; i++) {
146 if (i != 0)
147 sm_printf(", ");
148 sm_printf("%s", argv[i]);
150 sm_printf("\n");
151 return 0;
154 void sql_exec(struct sqlite3 *db, int (*callback)(void*, int, char**, char**), void *data, const char *sql)
156 char *err = NULL;
157 int rc;
159 if (!db)
160 return;
162 if (option_debug || debug_db) {
163 sm_msg("%s", sql);
164 if (strncasecmp(sql, "select", strlen("select")) == 0)
165 sqlite3_exec(db, sql, print_sql_output, NULL, NULL);
168 rc = sqlite3_exec(db, sql, callback, data, &err);
169 if (rc != SQLITE_OK && !parse_error) {
170 sm_ierror("%s:%d SQL error #2: %s\n", get_filename(), get_lineno(), err);
171 sm_ierror("%s:%d SQL: '%s'\n", get_filename(), get_lineno(), sql);
172 parse_error = 1;
176 static int replace_count;
177 static char **replace_table;
178 static const char *replace_return_ranges(const char *return_ranges)
180 int i;
182 if (!get_function()) {
183 /* I have no idea why EXPORT_SYMBOL() is here */
184 return return_ranges;
186 for (i = 0; i < replace_count; i += 3) {
187 if (strcmp(replace_table[i + 0], get_function()) == 0) {
188 if (strcmp(replace_table[i + 1], return_ranges) == 0)
189 return replace_table[i + 2];
192 return return_ranges;
195 static int delete_count;
196 static char **delete_table;
197 static bool is_delete_return(const char *return_ranges)
199 int i;
201 if (!get_function())
202 return false;
204 for (i = 0; i < delete_count; i += 2) {
205 if (strcmp(delete_table[i], get_function()) == 0 &&
206 strcmp(delete_table[i + 1], return_ranges) == 0)
207 return true;
210 return false;
213 void add_delete_return_hook(delete_hook *hook)
215 add_ptr_list(&delete_hooks, hook);
218 static bool is_project_delete_return(struct expression *expr)
220 delete_hook *hook;
222 FOR_EACH_PTR(delete_hooks, hook) {
223 if (hook(expr))
224 return true;
225 } END_FOR_EACH_PTR(hook);
226 return false;
229 static char *use_states;
230 static int get_db_state_count(void)
232 struct sm_state *sm;
233 int count = 0;
235 FOR_EACH_SM(__get_cur_stree(), sm) {
236 if (sm->owner == USHRT_MAX)
237 continue;
238 if (use_states[sm->owner])
239 count++;
240 } END_FOR_EACH_SM(sm);
241 return count;
244 static bool in_base_file(struct symbol *sym)
246 return sym->pos.stream == base_file_stream;
249 static bool is_local(struct symbol *sym)
251 if (sym->ctype.modifiers & MOD_STATIC)
252 return true;
253 if ((sym->ctype.modifiers & MOD_EXTERN) &&
254 (sym->ctype.modifiers & MOD_INLINE) &&
255 !in_base_file(sym))
256 return true;
258 if (!sym->definition)
259 return false;
261 if ((sym->definition->ctype.modifiers & MOD_EXTERN) &&
262 (sym->definition->ctype.modifiers & MOD_INLINE) &&
263 !in_base_file(sym->definition))
264 return true;
266 return false;
269 void db_ignore_states(int id)
271 use_states[id] = 0;
274 unsigned long long __fn_mtag;
275 static void set_fn_mtag(struct symbol *sym)
277 char buf[128];
279 if (is_local(cur_func_sym))
280 snprintf(buf, sizeof(buf), "%s %s", get_base_file(), get_function());
281 else
282 snprintf(buf, sizeof(buf), "extern %s", get_function());
284 __fn_mtag = str_to_mtag(buf);
287 void sql_insert_return_states(int return_id, const char *return_ranges,
288 int type, int param, const char *key, const char *value)
290 unsigned long long id;
293 if (key && strlen(key) >= 80)
294 return;
295 if (__inline_fn)
296 id = (unsigned long)__inline_fn;
297 else
298 id = __fn_mtag;
300 sql_insert(return_states, "0x%llx, '%s', %llu, %d, '%s', %d, %d, %d, '%s', '%s'",
301 get_base_file_id(), get_function(), id, return_id,
302 return_ranges, is_local(cur_func_sym), type, param, key, value);
305 static struct string_list *common_funcs;
306 static int is_common_function(const char *fn)
308 char *tmp;
310 if (!fn)
311 return 0;
313 if (strncmp(fn, "__builtin_", 10) == 0)
314 return 1;
316 FOR_EACH_PTR(common_funcs, tmp) {
317 if (strcmp(tmp, fn) == 0)
318 return 1;
319 } END_FOR_EACH_PTR(tmp);
321 return 0;
324 static char *function_signature(void)
326 return type_to_str(get_real_base_type(cur_func_sym));
329 void sql_insert_caller_info(struct expression *call, int type,
330 int param, const char *key, const char *value)
332 FILE *tmp_fd = sm_outfd;
333 char *fn;
335 if (!option_info && !__inline_call)
336 return;
337 if (unreachable())
338 return;
340 if (key && strlen(key) >= 80)
341 return;
343 fn = get_fnptr_name(call->fn);
344 if (!fn)
345 return;
347 if (__inline_call) {
348 mem_sql(NULL, NULL,
349 "insert into caller_info values (0x%llx, '%s', '%s', %lu, %d, %d, %d, '%s', '%s');",
350 get_base_file_id(), get_function(), fn, (unsigned long)call,
351 is_static(call->fn), type, param, key, value);
354 if (!option_info)
355 return;
357 if (strncmp(fn, "__builtin_", 10) == 0)
358 return;
359 if (type != INTERNAL && is_common_function(fn))
360 return;
362 sm_outfd = caller_info_fd;
363 sm_msg("SQL_caller_info: insert into caller_info values ("
364 "0x%llx, '%s', '%s', %%CALL_ID%%, %d, %d, %d, '%s', '%s');",
365 get_base_file_id(), get_function(), fn, is_static(call->fn),
366 type, param, key, value);
367 sm_outfd = tmp_fd;
369 free_string(fn);
372 void sql_insert_function_ptr(const char *fn, const char *struct_name)
374 sql_insert_or_ignore(function_ptr, "0x%llx, '%s', '%s', 0",
375 get_base_file_id(), fn, struct_name);
378 void sql_insert_return_implies(int type, int param, const char *key, const char *value)
380 unsigned long long id;
382 if (__inline_fn)
383 id = (unsigned long)__inline_fn;
384 else
385 id = __fn_mtag;
387 sql_insert_or_ignore(return_implies, "0x%llx, '%s', %llu, %d, %d, %d, '%s', '%s'",
388 get_base_file_id(), get_function(), id, fn_static(), type,
389 param, key, value);
392 void sql_insert_call_implies(int type, int param, const char *key, const char *value)
394 sql_insert_or_ignore(call_implies, "0x%llx, '%s', %lu, %d, %d, %d, '%s', '%s'",
395 get_base_file_id(), get_function(), (unsigned long)__inline_fn,
396 fn_static(), type, param, key, value);
399 void sql_insert_function_type_size(const char *member, const char *ranges)
401 sql_insert(function_type_size, "0x%llx, '%s', '%s', '%s'", get_base_file_id(), get_function(), member, ranges);
404 void sql_insert_function_type_info(int type, const char *struct_type, const char *member, const char *value)
406 sql_insert(function_type_info, "0x%llx, '%s', %d, '%s', '%s', '%s'", get_base_file_id(), get_function(), type, struct_type, member, value);
409 void sql_insert_type_info(int type, const char *member, const char *value)
411 sql_insert_cache(type_info, "0x%llx, %d, '%s', '%s'", get_base_file_id(), type, member, value);
414 void sql_insert_local_values(const char *name, const char *value)
416 sql_insert(local_values, "0x%llx, '%s', '%s'", get_base_file_id(), name, value);
419 void sql_insert_function_type_value(const char *type, const char *value)
421 sql_insert(function_type_value, "0x%llx, '%s', '%s', '%s'", get_base_file_id(), get_function(), type, value);
424 void sql_insert_function_type(int param, const char *value)
426 sql_insert(function_type, "0x%llx, '%s', %d, %d, '%s'",
427 get_base_file_id(), get_function(), fn_static(), param, value);
430 void sql_insert_parameter_name(int param, const char *value)
432 sql_insert(parameter_name, "0x%llx, '%s', %d, %d, '%s'",
433 get_base_file_id(), get_function(), fn_static(), param, value);
436 void sql_insert_data_info(struct expression *data, int type, const char *value)
438 char *data_name;
440 data_name = get_data_info_name(data);
441 if (!data_name)
442 return;
443 sql_insert(data_info, "0x%llx, '%s', %d, '%s'",
444 is_static(data) ? get_base_file_id() : 0,
445 data_name, type, value);
448 void sql_insert_data_info_var_sym(const char *var, struct symbol *sym, int type, const char *value)
450 sql_insert(data_info, "0x%llx, '%s', %d, '%s'",
451 (sym->ctype.modifiers & MOD_STATIC) ? get_base_file_id() : 0,
452 var, type, value);
455 void sql_save_constraint(const char *con)
457 if (!option_info)
458 return;
460 sm_msg("SQL: insert or ignore into constraints (str) values('%s');", escape_newlines(con));
463 void sql_save_constraint_required(const char *data, int op, const char *limit)
465 sql_insert_or_ignore(constraints_required, "'%s', '%s', '%s'", data, show_special(op), limit);
468 void sql_copy_constraint_required(const char *new_limit, const char *old_limit)
470 if (!option_info)
471 return;
473 sm_msg("SQL_late: insert or ignore into constraints_required (data, op, bound) "
474 "select constraints_required.data, constraints_required.op, '%s' from "
475 "constraints_required where bound = '%s';", new_limit, old_limit);
478 void sql_insert_fn_ptr_data_link(const char *ptr, const char *data)
480 sql_insert_or_ignore(fn_ptr_data_link, "'%s', '%s'", ptr, data);
483 void sql_insert_fn_data_link(struct expression *fn, int type, int param, const char *key, const char *value)
485 if (fn->type != EXPR_SYMBOL || !fn->symbol->ident)
486 return;
488 sql_insert(fn_data_link, "0x%llx, '%s', %d, %d, %d, '%s', '%s'",
489 is_local(fn->symbol) ? get_base_file_id() : 0,
490 fn->symbol->ident->name,
491 is_local(fn->symbol),
492 type, param, key, value);
495 void sql_insert_mtag_about(mtag_t tag, const char *left_name, const char *right_name)
497 sql_insert_cache(mtag_about, "%lld, '%s', '%s', %d, '%s', '%s'",
498 tag, get_filename(), get_function(), get_lineno(),
499 left_name, right_name);
502 void sql_insert_mtag_info(mtag_t tag, int type, const char *value)
504 sql_insert_cache(mtag_info, "'%s', %lld, %d, '%s'", get_filename(), tag, type, value);
507 void sql_insert_mtag_map(mtag_t container, int container_offset, mtag_t tag, int tag_offset)
509 sql_insert(mtag_map, "%lld, %d, %lld, %d", container, container_offset, tag, tag_offset);
512 void sql_insert_mtag_alias(mtag_t orig, mtag_t alias)
514 sql_insert(mtag_alias, "%lld, %lld", orig, alias);
517 static int save_mtag(void *_tag, int argc, char **argv, char **azColName)
519 mtag_t *saved_tag = _tag;
520 mtag_t new_tag;
522 new_tag = strtoll(argv[0], NULL, 10);
524 if (!*saved_tag)
525 *saved_tag = new_tag;
526 else if (*saved_tag != new_tag)
527 *saved_tag = -1ULL;
529 return 0;
532 int mtag_map_select_container(mtag_t tag, int container_offset, mtag_t *container)
534 mtag_t tmp = 0;
536 run_sql(save_mtag, &tmp,
537 "select container from mtag_map where tag = %lld and container_offset = %d and tag_offset = 0;",
538 tag, container_offset);
540 if (tmp == 0 || tmp == -1ULL)
541 return 0;
542 *container = tmp;
543 return 1;
546 int mtag_map_select_tag(mtag_t container, int offset, mtag_t *tag)
548 mtag_t tmp = 0;
550 run_sql(save_mtag, &tmp,
551 "select tag from mtag_map where container = %lld and container_offset = %d;",
552 container, offset);
554 if (tmp == 0 || tmp == -1ULL)
555 return 0;
556 *tag = tmp;
557 return 1;
560 char *get_static_filter(struct symbol *sym)
562 static char sql_filter[1024];
564 /* This can only happen on buggy code. Return invalid SQL. */
565 if (!sym) {
566 sql_filter[0] = '\0';
567 return sql_filter;
570 if (is_local(sym)) {
571 snprintf(sql_filter, sizeof(sql_filter),
572 "file = 0x%llx and function = '%s' and static = '1'",
573 get_base_file_id(), sym->ident->name);
574 } else {
575 snprintf(sql_filter, sizeof(sql_filter),
576 "function = '%s' and static = '0'", sym->ident->name);
579 return sql_filter;
582 static int get_row_count(void *_row_count, int argc, char **argv, char **azColName)
584 int *row_count = _row_count;
586 *row_count = 0;
587 if (argc != 1)
588 return 0;
589 *row_count = atoi(argv[0]);
590 return 0;
593 static void sql_select_return_states_pointer(const char *cols,
594 struct expression *call, int (*callback)(void*, int, char**, char**), void *info)
596 char *ptr;
597 int return_count = 0;
599 ptr = get_fnptr_name(call->fn);
600 if (!ptr)
601 return;
603 run_sql(get_row_count, &return_count,
604 "select count(*) from return_states join function_ptr "
605 "where return_states.function == function_ptr.function and "
606 "ptr = '%s' and searchable = 1 and type = %d;", ptr, INTERNAL);
607 /* The magic number 100 is just from testing on the kernel. */
608 if (return_count == 0 || return_count > 100) {
609 run_sql(callback, info,
610 "select distinct %s from return_states join function_ptr where "
611 "return_states.function == function_ptr.function and ptr = '%s' "
612 "and searchable = 1 and type = %d "
613 "order by function_ptr.file, return_states.file, return_id, type;",
614 cols, ptr, INTERNAL);
615 mark_call_params_untracked(call);
616 return;
619 run_sql(callback, info,
620 "select %s from return_states join function_ptr where "
621 "return_states.function == function_ptr.function and ptr = '%s' "
622 "and searchable = 1 "
623 "order by function_ptr.file, return_states.file, return_id, type;",
624 cols, ptr);
627 static int is_local_symbol(struct expression *expr)
629 if (expr->type != EXPR_SYMBOL)
630 return 0;
631 if (expr->symbol->ctype.modifiers & (MOD_NONLOCAL | MOD_STATIC | MOD_ADDRESSABLE))
632 return 0;
633 return 1;
636 bool is_fn_ptr(struct expression *fn)
638 fn = strip_expr(fn);
639 if (fn->type != EXPR_SYMBOL)
640 return true;
641 if (!fn->symbol)
642 return true;
643 if (is_local_symbol(fn))
644 return true;
645 return false;
648 void sql_select_return_states(const char *cols, struct expression *call,
649 int (*callback)(void*, int, char**, char**), void *info)
651 struct expression *fn;
652 int row_count = 0;
654 if (is_fake_call(call))
655 return;
657 fn = strip_expr(call->fn);
658 if (is_fn_ptr(fn)) {
659 sql_select_return_states_pointer(cols, call, callback, info);
660 return;
663 if (inlinable(fn)) {
664 mem_sql(callback, info,
665 "select %s from return_states where call_id = '%lu' order by return_id, type;",
666 cols, (unsigned long)call);
667 return;
670 run_sql(get_row_count, &row_count, "select count(*) from return_states where %s;",
671 get_static_filter(fn->symbol));
672 if (row_count == 0 && fn->symbol && fn->symbol->definition)
673 set_state(my_id, "db_incomplete", NULL, &incomplete);
674 if (row_count == 0 || row_count > 3000) {
675 mark_call_params_untracked(call);
676 return;
679 run_sql(callback, info, "select %s from return_states where %s order by file, return_id, type;",
680 cols, get_static_filter(fn->symbol));
683 bool db_incomplete(void)
685 return !!get_state(my_id, "db_incomplete", NULL);
688 #define CALL_IMPLIES 0
689 #define RETURN_IMPLIES 1
691 struct implies_info {
692 int type;
693 struct db_implies_cb_list *cb_list;
694 struct expression *expr;
695 struct symbol *sym;
698 void sql_select_implies(const char *cols, struct implies_info *info,
699 int (*callback)(void*, int, char**, char**))
701 if (info->type == RETURN_IMPLIES && inlinable(info->expr->fn)) {
702 mem_sql(callback, info,
703 "select %s from return_implies where call_id = '%lu';",
704 cols, (unsigned long)info->expr);
705 return;
708 run_sql(callback, info, "select %s from %s_implies where %s;",
709 cols,
710 info->type == CALL_IMPLIES ? "call" : "return",
711 get_static_filter(info->sym));
714 struct select_caller_info_data {
715 struct stree *final_states;
716 struct timeval start_time;
717 int prev_func_id;
718 int ignore;
719 int results;
722 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName);
724 static void sql_select_caller_info(struct select_caller_info_data *data,
725 const char *cols, struct symbol *sym)
727 if (__inline_fn) {
728 mem_sql(caller_info_callback, data,
729 "select %s from caller_info where call_id = %lu;",
730 cols, (unsigned long)__inline_fn);
731 return;
734 if (is_common_function(sym->ident->name))
735 return;
736 run_sql(caller_info_callback, data,
737 "select %s from common_caller_info where %s order by call_id;",
738 cols, get_static_filter(sym));
739 if (data->results)
740 return;
742 run_sql(caller_info_callback, data,
743 "select %s from caller_info where %s order by call_id;",
744 cols, get_static_filter(sym));
747 void select_caller_info_hook(void (*callback)(const char *name, struct symbol *sym, char *key, char *value), int type)
749 struct def_callback *def_callback = __alloc_def_callback(0);
751 def_callback->hook_type = type;
752 def_callback->callback = callback;
753 add_ptr_list(&select_caller_info_callbacks, def_callback);
756 void select_caller_name_sym(void (*fn)(const char *name, struct symbol *sym, char *value), int type)
758 struct def_name_sym_callback *callback = __alloc_def_name_sym_callback(0);
760 callback->hook_type = type;
761 callback->callback = fn;
762 add_ptr_list(&select_caller_name_sym_callbacks, callback);
766 * These call backs are used when the --info option is turned on to print struct
767 * member information. For example foo->bar could have a state in
768 * smatch_extra.c and also check_user.c.
770 void add_member_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
772 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
774 member_callback->owner = owner;
775 member_callback->callback = callback;
776 add_ptr_list(&member_callbacks, member_callback);
779 void add_caller_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
781 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
783 member_callback->owner = owner;
784 member_callback->callback = callback;
785 add_ptr_list(&member_callbacks_new, member_callback);
788 void add_return_info_callback(int owner,
789 void (*callback)(int return_id, char *return_ranges,
790 struct expression *returned_expr,
791 int param,
792 const char *printed_name,
793 struct sm_state *sm))
795 struct return_info_callback *return_callback = __alloc_return_info_callback(0);
797 return_callback->owner = owner;
798 return_callback->callback = callback;
799 add_ptr_list(&return_callbacks, return_callback);
802 void add_split_return_callback(void (*fn)(int return_id, char *return_ranges, struct expression *returned_expr))
804 struct returned_state_callback *callback = __alloc_returned_state_callback(0);
806 callback->callback = fn;
807 add_ptr_list(&returned_state_callbacks, callback);
810 void add_returned_member_callback(int owner, void (*callback)(int return_id, char *return_ranges, struct expression *expr, char *printed_name, struct smatch_state *state))
812 struct returned_member_callback *member_callback = __alloc_returned_member_callback(0);
814 member_callback->owner = owner;
815 member_callback->callback = callback;
816 add_ptr_list(&returned_member_callbacks, member_callback);
819 void select_call_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
821 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
823 cb->type = type;
824 cb->callback = callback;
825 add_ptr_list(&call_implies_cb_list, cb);
828 void select_return_implies_hook_early(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
830 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
832 cb->type = type;
833 cb->callback = callback;
834 add_ptr_list(&return_implies_cb_list_early, cb);
837 void select_return_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
839 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
841 cb->type = type;
842 cb->callback = callback;
843 add_ptr_list(&return_implies_cb_list_late, cb);
846 struct return_info {
847 struct expression *static_returns_call;
848 struct symbol *return_type;
849 struct range_list *return_range_list;
852 static int db_return_callback(void *_ret_info, int argc, char **argv, char **azColName)
854 struct return_info *ret_info = _ret_info;
855 struct range_list *rl;
856 struct expression *call_expr = ret_info->static_returns_call;
858 if (argc != 1)
859 return 0;
860 call_results_to_rl(call_expr, ret_info->return_type, argv[0], &rl);
861 ret_info->return_range_list = rl_union(ret_info->return_range_list, rl);
862 return 0;
865 static struct expression *cached_expr, *cached_no_args;
866 static const char *cached_str;
867 static struct range_list *cached_rl, *cached_str_rl, *cached_no_args_rl;
869 static void clear_cached_return_vals(void)
871 cached_expr = NULL;
872 cached_rl = NULL;
873 cached_str = NULL;
874 cached_str_rl = NULL;
875 cached_no_args = NULL;
876 cached_no_args_rl = NULL;
879 struct range_list *db_return_vals(struct expression *expr)
881 struct return_info ret_info = {};
882 struct sm_state *sm;
884 if (!expr)
885 return NULL;
887 if (is_fake_call(expr))
888 return NULL;
890 if (expr == cached_expr)
891 return clone_rl(cached_rl);
893 cached_expr = expr;
894 cached_rl = NULL;
896 sm = get_extra_sm_state(expr);
897 if (sm) {
898 cached_rl = clone_rl(estate_rl(sm->state));
899 return clone_rl(estate_rl(sm->state));
901 ret_info.static_returns_call = expr;
902 ret_info.return_type = get_type(expr);
903 if (!ret_info.return_type)
904 return NULL;
906 if (expr->fn->type != EXPR_SYMBOL || !expr->fn->symbol)
907 return NULL;
909 ret_info.return_range_list = NULL;
910 if (inlinable(expr->fn)) {
911 mem_sql(db_return_callback, &ret_info,
912 "select distinct return from return_states where call_id = '%lu';",
913 (unsigned long)expr);
914 } else {
915 run_sql(db_return_callback, &ret_info,
916 "select distinct return from return_states where %s;",
917 get_static_filter(expr->fn->symbol));
919 cached_rl = clone_rl(ret_info.return_range_list);
920 return ret_info.return_range_list;
923 struct range_list *db_return_vals_from_str(const char *fn_name)
925 struct return_info ret_info;
927 if (!fn_name)
928 return NULL;
929 if (fn_name == cached_str)
930 return clone_rl(cached_str_rl);
931 cached_str = fn_name;
932 cached_str_rl = NULL;
934 ret_info.static_returns_call = NULL;
935 ret_info.return_type = &llong_ctype;
936 ret_info.return_range_list = NULL;
938 run_sql(db_return_callback, &ret_info,
939 "select distinct return from return_states where function = '%s';",
940 fn_name);
941 cached_str_rl = clone_rl(ret_info.return_range_list);
942 return ret_info.return_range_list;
946 * This is used when we have a function that takes a function pointer as a
947 * parameter. "frob(blah, blah, my_function);" We know that the return values
948 * from frob() come from my_funcion() so we want to find the possible returns
949 * of my_function(), but we don't know which arguments are passed to it.
952 struct range_list *db_return_vals_no_args(struct expression *expr)
954 struct return_info ret_info = {};
956 if (!expr || expr->type != EXPR_SYMBOL)
957 return NULL;
959 if (expr == cached_no_args)
960 return clone_rl(cached_no_args_rl);
961 cached_no_args = expr;
962 cached_no_args_rl = NULL;
964 ret_info.static_returns_call = expr;
965 ret_info.return_type = get_type(expr);
966 ret_info.return_type = get_real_base_type(ret_info.return_type);
967 if (!ret_info.return_type)
968 return NULL;
970 run_sql(db_return_callback, &ret_info,
971 "select distinct return from return_states where %s;",
972 get_static_filter(expr->symbol));
974 cached_no_args_rl = clone_rl(ret_info.return_range_list);
975 return ret_info.return_range_list;
978 static void match_call_marker(struct expression *expr)
980 struct symbol *type;
982 type = get_type(expr->fn);
983 if (type && type->type == SYM_PTR)
984 type = get_real_base_type(type);
987 * we just want to record something in the database so that if we have
988 * two calls like: frob(4); frob(some_unkown); then on the receiving
989 * side we know that sometimes frob is called with unknown parameters.
992 sql_insert_caller_info(expr, INTERNAL, -1, "%call_marker%", type_to_str(type));
995 int is_recursive_member(const char *name)
997 char buf[256];
998 const char *p, *next;
999 int size;
1001 p = strchr(name, '>');
1002 if (!p)
1003 return 0;
1004 p++;
1005 while (true) {
1006 next = strchr(p, '>');
1007 if (!next)
1008 return 0;
1009 next++;
1011 size = next - p;
1012 if (size >= sizeof(buf))
1013 return 0;
1014 memcpy(buf, p, size);
1015 buf[size] = '\0';
1016 if (strstr(next, buf))
1017 return 1;
1018 p = next;
1022 char *sm_to_arg_name(struct expression *expr, struct sm_state *sm)
1024 struct symbol *sym;
1025 const char *sm_name;
1026 char *name;
1027 bool is_address = false;
1028 bool add_star = false;
1029 char buf[256];
1030 char *ret = NULL;
1031 int len;
1033 expr = strip_expr(expr);
1034 if (!expr)
1035 return NULL;
1037 if (expr->type == EXPR_PREOP && expr->op == '&') {
1038 expr = strip_expr(expr->unop);
1039 is_address = true;
1042 name = expr_to_var_sym(expr, &sym);
1043 if (!name || !sym)
1044 goto free;
1045 if (sym != sm->sym)
1046 goto free;
1048 sm_name = sm->name;
1049 add_star = false;
1050 if (sm_name[0] == '*') {
1051 add_star = true;
1052 sm_name++;
1055 len = strlen(name);
1056 if (strncmp(name, sm_name, len) != 0)
1057 goto free;
1058 if (sm_name[len] == '\0') {
1059 snprintf(buf, sizeof(buf), "%s%s$",
1060 add_star ? "*" : "", is_address ? "*" : "");
1061 } else {
1062 if (sm_name[len] != '.' && sm_name[len] != '-')
1063 goto free;
1064 if (sm_name[len] == '-')
1065 len++;
1066 // FIXME does is_address really imply that sm_name[len] == '-'
1067 snprintf(buf, sizeof(buf), "%s$->%s", add_star ? "*" : "",
1068 sm_name + len);
1071 ret = alloc_sname(buf);
1072 free:
1073 free_string(name);
1074 return ret;
1077 static void print_struct_members(struct expression *call, struct expression *expr, int param,
1078 int owner,
1079 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm),
1080 bool new)
1082 struct sm_state *sm;
1083 const char *sm_name;
1084 char *name;
1085 struct symbol *sym;
1086 int len;
1087 char printed_name[256];
1088 int is_address = 0;
1089 bool add_star;
1090 struct symbol *type;
1092 expr = strip_expr(expr);
1093 if (!expr)
1094 return;
1095 type = get_type(expr);
1096 if (!new && type && type_bits(type) < type_bits(&ulong_ctype))
1097 return;
1099 if (expr->type == EXPR_PREOP && expr->op == '&') {
1100 expr = strip_expr(expr->unop);
1101 is_address = 1;
1104 name = expr_to_var_sym(expr, &sym);
1105 if (!name || !sym)
1106 goto free;
1108 len = strlen(name);
1109 FOR_EACH_SM(__get_cur_stree(), sm) {
1110 if (sm->owner != owner || sm->sym != sym)
1111 continue;
1113 sm_name = sm->name;
1114 add_star = false;
1115 if (sm_name[0] == '*') {
1116 add_star = true;
1117 sm_name++;
1119 // FIXME: simplify?
1120 if (!add_star && strcmp(name, sm_name) == 0) {
1121 if (is_address) {
1122 snprintf(printed_name, sizeof(printed_name), "*$");
1123 } else {
1124 if (new)
1125 snprintf(printed_name, sizeof(printed_name), "$");
1126 else
1127 continue;
1129 } else if (add_star && strcmp(name, sm_name) == 0) {
1130 snprintf(printed_name, sizeof(printed_name), "%s*$",
1131 is_address ? "*" : "");
1132 } else if (strncmp(name, sm_name, len) == 0) {
1133 if (sm_name[len] != '.' && sm_name[len] != '-')
1134 continue;
1135 if (is_address && sm_name[len] == '.') {
1136 snprintf(printed_name, sizeof(printed_name),
1137 "%s$->%s", add_star ? "*" : "",
1138 sm_name + len + 1);
1139 } else if (is_address && sm_name[len] == '-') {
1140 snprintf(printed_name, sizeof(printed_name),
1141 "%s(*$)%s", add_star ? "*" : "",
1142 sm_name + len);
1143 } else {
1144 snprintf(printed_name, sizeof(printed_name),
1145 "%s$%s", add_star ? "*" : "",
1146 sm_name + len);
1148 } else if (sm_name[0] == '&' && strncmp(name, sm_name + 1, len) == 0) {
1149 if (sm_name[len + 1] != '.' && sm_name[len + 1] != '-')
1150 continue;
1151 if (is_address && sm_name[len + 1] == '.') {
1152 snprintf(printed_name, sizeof(printed_name),
1153 "&%s$->%s", add_star ? "*" : "",
1154 sm_name + len + 2);
1155 } else if (is_address && sm_name[len] == '-') {
1156 snprintf(printed_name, sizeof(printed_name),
1157 "&%s(*$)%s", add_star ? "*" : "",
1158 sm_name + len + 1);
1159 } else {
1160 snprintf(printed_name, sizeof(printed_name),
1161 "&%s$%s", add_star ? "*" : "",
1162 sm_name + len + 1);
1164 } else {
1165 continue;
1167 if (is_recursive_member(printed_name))
1168 continue;
1169 callback(call, param, printed_name, sm);
1170 } END_FOR_EACH_SM(sm);
1171 free:
1172 free_string(name);
1175 static void match_call_info(struct expression *call)
1177 struct member_info_callback *cb;
1178 struct expression *arg;
1179 int i;
1181 FOR_EACH_PTR(member_callbacks, cb) {
1182 i = -1;
1183 FOR_EACH_PTR(call->args, arg) {
1184 i++;
1185 print_struct_members(call, arg, i, cb->owner, cb->callback, 0);
1186 } END_FOR_EACH_PTR(arg);
1187 } END_FOR_EACH_PTR(cb);
1190 static struct expression *get_fake_variable(struct expression *expr)
1192 struct expression *tmp;
1194 tmp = expr_get_fake_parent_expr(expr);
1195 if (!tmp || tmp->type != EXPR_ASSIGNMENT)
1196 return NULL;
1198 return tmp->left;
1201 static struct sm_state *get_returned_sm(struct expression *expr)
1203 struct expression *fake;
1205 fake = get_fake_variable(expr);
1206 if (fake)
1207 expr = fake;
1209 return get_sm_state_expr(SMATCH_EXTRA, expr);
1212 static void match_call_info_new(struct expression *call)
1214 struct member_info_callback *cb;
1215 struct expression *arg, *tmp;
1216 int i;
1218 if (!option_info && !__inline_call && !local_debug)
1219 return;
1221 FOR_EACH_PTR(member_callbacks_new, cb) {
1222 i = -1;
1223 FOR_EACH_PTR(call->args, arg) {
1224 i++;
1225 tmp = get_fake_variable(arg);
1226 if (!tmp)
1227 tmp = arg;
1228 __ignore_param_used++;
1229 print_struct_members(call, tmp, i, cb->owner, cb->callback, 1);
1230 __ignore_param_used--;
1231 } END_FOR_EACH_PTR(arg);
1232 } END_FOR_EACH_PTR(cb);
1235 static int get_param(int param, char **name, struct symbol **sym)
1237 struct symbol *arg;
1238 int i;
1240 i = 0;
1241 FOR_EACH_PTR(cur_func_sym->ctype.base_type->arguments, arg) {
1242 if (i == param) {
1243 *name = arg->ident->name;
1244 *sym = arg;
1245 return TRUE;
1247 i++;
1248 } END_FOR_EACH_PTR(arg);
1250 return FALSE;
1253 static int function_signature_matches(const char *sig)
1255 char *my_sig;
1257 my_sig = function_signature();
1258 if (!sig || !my_sig)
1259 return 1; /* default to matching */
1260 if (strcmp(my_sig, sig) == 0)
1261 return 1;
1262 return 0;
1265 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName)
1267 struct select_caller_info_data *data = _data;
1268 int func_id;
1269 long type;
1270 long param;
1271 char *key;
1272 char *value;
1273 char *name = NULL;
1274 struct symbol *sym = NULL;
1275 struct def_callback *def_callback;
1276 struct def_name_sym_callback *ns_callback;
1277 struct stree *stree;
1278 struct timeval cur_time;
1279 char fullname[256];
1280 char *p;
1282 data->results = 1;
1284 if (argc != 5)
1285 return 0;
1287 gettimeofday(&cur_time, NULL);
1288 if (cur_time.tv_sec - data->start_time.tv_sec > 10)
1289 return 0;
1291 func_id = atoi(argv[0]);
1292 errno = 0;
1293 type = strtol(argv[1], NULL, 10);
1294 param = strtol(argv[2], NULL, 10);
1295 if (errno)
1296 return 0;
1297 key = argv[3];
1298 value = argv[4];
1300 if (data->prev_func_id == -1)
1301 data->prev_func_id = func_id;
1302 if (func_id != data->prev_func_id) {
1303 stree = __pop_fake_cur_stree();
1304 if (!data->ignore)
1305 merge_stree(&data->final_states, stree);
1306 free_stree(&stree);
1307 __push_fake_cur_stree();
1308 __unnullify_path();
1309 data->prev_func_id = func_id;
1310 data->ignore = 0;
1313 if (data->ignore)
1314 return 0;
1315 if (type == INTERNAL &&
1316 !function_signature_matches(value)) {
1317 data->ignore = 1;
1318 return 0;
1321 if (param >= 0 && !get_param(param, &name, &sym))
1322 return 0;
1324 FOR_EACH_PTR(select_caller_info_callbacks, def_callback) {
1325 if (def_callback->hook_type == type)
1326 def_callback->callback(name, sym, key, value);
1327 } END_FOR_EACH_PTR(def_callback);
1329 p = strchr(key, '$');
1330 if (name && p)
1331 snprintf(fullname, sizeof(fullname), "%.*s%s%s", (int)(p - key), key, name, p + 1);
1332 else
1333 snprintf(fullname, sizeof(fullname), "%s", key);
1335 FOR_EACH_PTR(select_caller_name_sym_callbacks, ns_callback) {
1336 if (ns_callback->hook_type == type)
1337 ns_callback->callback(fullname, sym, value);
1338 } END_FOR_EACH_PTR(ns_callback);
1340 return 0;
1343 static struct string_list *ptr_names_done;
1344 static struct string_list *ptr_names;
1346 static int get_ptr_name(void *unused, int argc, char **argv, char **azColName)
1348 insert_string(&ptr_names, alloc_string(argv[0]));
1349 return 0;
1352 static char *get_next_ptr_name(void)
1354 char *ptr;
1356 FOR_EACH_PTR(ptr_names, ptr) {
1357 if (!insert_string(&ptr_names_done, ptr))
1358 continue;
1359 return ptr;
1360 } END_FOR_EACH_PTR(ptr);
1361 return NULL;
1364 static void get_ptr_names(unsigned long long file, const char *name)
1366 char sql_filter[1024];
1367 int before, after;
1369 if (file) {
1370 snprintf(sql_filter, 1024, "file = 0x%llx and function = '%s';",
1371 file, name);
1372 } else {
1373 snprintf(sql_filter, 1024, "function = '%s';", name);
1376 before = ptr_list_size((struct ptr_list *)ptr_names);
1378 run_sql(get_ptr_name, NULL,
1379 "select distinct ptr from function_ptr where %s",
1380 sql_filter);
1382 after = ptr_list_size((struct ptr_list *)ptr_names);
1383 if (before == after)
1384 return;
1386 while ((name = get_next_ptr_name()))
1387 get_ptr_names(0, name);
1390 static void match_data_from_db(struct symbol *sym)
1392 struct select_caller_info_data data = { .prev_func_id = -1 };
1393 struct sm_state *sm;
1394 struct stree *stree;
1395 struct timeval end_time;
1397 if (!sym || !sym->ident)
1398 return;
1400 set_fn_mtag(sym);
1401 gettimeofday(&data.start_time, NULL);
1403 __push_fake_cur_stree();
1404 __unnullify_path();
1406 if (!__inline_fn) {
1407 char *ptr;
1409 if (sym->ctype.modifiers & MOD_STATIC)
1410 get_ptr_names(get_base_file_id(), sym->ident->name);
1411 else
1412 get_ptr_names(0, sym->ident->name);
1414 if (ptr_list_size((struct ptr_list *)ptr_names) > 20) {
1415 __free_ptr_list((struct ptr_list **)&ptr_names);
1416 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1417 __free_fake_cur_stree();
1418 return;
1421 sql_select_caller_info(&data,
1422 "call_id, type, parameter, key, value",
1423 sym);
1426 stree = __pop_fake_cur_stree();
1427 if (!data.ignore)
1428 merge_stree(&data.final_states, stree);
1429 free_stree(&stree);
1430 __push_fake_cur_stree();
1431 __unnullify_path();
1432 data.prev_func_id = -1;
1433 data.ignore = 0;
1434 data.results = 0;
1436 FOR_EACH_PTR(ptr_names, ptr) {
1437 run_sql(caller_info_callback, &data,
1438 "select call_id, type, parameter, key, value"
1439 " from common_caller_info where function = '%s' order by call_id",
1440 ptr);
1441 } END_FOR_EACH_PTR(ptr);
1443 if (data.results) {
1444 FOR_EACH_PTR(ptr_names, ptr) {
1445 free_string(ptr);
1446 } END_FOR_EACH_PTR(ptr);
1447 goto free_ptr_names;
1450 FOR_EACH_PTR(ptr_names, ptr) {
1451 run_sql(caller_info_callback, &data,
1452 "select call_id, type, parameter, key, value"
1453 " from caller_info where function = '%s' order by call_id",
1454 ptr);
1455 free_string(ptr);
1456 } END_FOR_EACH_PTR(ptr);
1458 free_ptr_names:
1459 __free_ptr_list((struct ptr_list **)&ptr_names);
1460 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1461 } else {
1462 sql_select_caller_info(&data,
1463 "call_id, type, parameter, key, value",
1464 sym);
1467 stree = __pop_fake_cur_stree();
1468 if (!data.ignore)
1469 merge_stree(&data.final_states, stree);
1470 free_stree(&stree);
1472 gettimeofday(&end_time, NULL);
1473 if (end_time.tv_sec - data.start_time.tv_sec <= 10) {
1474 FOR_EACH_SM(data.final_states, sm) {
1475 __set_sm(sm);
1476 } END_FOR_EACH_SM(sm);
1479 free_stree(&data.final_states);
1482 static int return_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1484 struct implies_info *info = _info;
1485 struct db_implies_callback *cb;
1486 struct expression *arg = NULL;
1487 int type;
1488 int param;
1490 if (argc != 5)
1491 return 0;
1493 type = atoi(argv[1]);
1494 param = atoi(argv[2]);
1496 FOR_EACH_PTR(info->cb_list, cb) {
1497 if (cb->type != type)
1498 continue;
1499 if (param != -1) {
1500 arg = get_argument_from_call_expr(info->expr->args, param);
1501 if (!arg)
1502 continue;
1504 cb->callback(info->expr, arg, argv[3], argv[4]);
1505 } END_FOR_EACH_PTR(cb);
1507 return 0;
1510 static int call_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1512 struct implies_info *info = _info;
1513 struct db_implies_callback *cb;
1514 struct expression *arg;
1515 struct symbol *sym;
1516 char *name;
1517 int type;
1518 int param;
1520 if (argc != 5)
1521 return 0;
1523 type = atoi(argv[1]);
1524 param = atoi(argv[2]);
1526 if (!get_param(param, &name, &sym))
1527 return 0;
1528 arg = symbol_expression(sym);
1529 if (!arg)
1530 return 0;
1532 FOR_EACH_PTR(info->cb_list, cb) {
1533 if (cb->type != type)
1534 continue;
1535 cb->callback(info->expr, arg, argv[3], argv[4]);
1536 } END_FOR_EACH_PTR(cb);
1538 return 0;
1541 static void match_return_implies_helper(struct expression *expr, struct db_implies_cb_list *cb_list)
1543 struct implies_info info = {
1544 .type = RETURN_IMPLIES,
1545 .cb_list = cb_list,
1548 if (expr->fn->type != EXPR_SYMBOL ||
1549 !expr->fn->symbol)
1550 return;
1551 info.expr = expr;
1552 info.sym = expr->fn->symbol;
1553 sql_select_implies("function, type, parameter, key, value", &info,
1554 return_implies_callbacks);
1557 static void match_return_implies_early(struct expression *expr)
1559 match_return_implies_helper(expr, return_implies_cb_list_early);
1562 static void match_return_implies_late(struct expression *expr)
1564 match_return_implies_helper(expr, return_implies_cb_list_late);
1567 static void match_call_implies(struct symbol *sym)
1569 struct implies_info info = {
1570 .type = CALL_IMPLIES,
1571 .cb_list = call_implies_cb_list,
1574 if (!sym || !sym->ident)
1575 return;
1577 info.sym = sym;
1578 sql_select_implies("function, type, parameter, key, value", &info,
1579 call_implies_callbacks);
1582 static char *get_fn_param_str(struct expression *expr)
1584 struct expression *tmp;
1585 int param;
1586 char buf[32];
1588 tmp = get_assigned_expr(expr);
1589 if (tmp)
1590 expr = tmp;
1591 expr = strip_expr(expr);
1592 if (!expr || expr->type != EXPR_CALL)
1593 return NULL;
1594 expr = strip_expr(expr->fn);
1595 if (!expr || expr->type != EXPR_SYMBOL)
1596 return NULL;
1597 param = get_param_num(expr);
1598 if (param < 0)
1599 return NULL;
1601 snprintf(buf, sizeof(buf), "[r $%d]", param);
1602 return alloc_sname(buf);
1605 static char *get_return_compare_is_param(struct expression *expr)
1607 char *var;
1608 char buf[256];
1609 int comparison;
1610 int param;
1612 param = get_param_num(expr);
1613 if (param < 0)
1614 return NULL;
1616 var = expr_to_var(expr);
1617 if (!var)
1618 return NULL;
1619 snprintf(buf, sizeof(buf), "%s orig", var);
1620 comparison = get_comparison_strings(var, buf);
1621 free_string(var);
1623 if (!comparison)
1624 return NULL;
1626 snprintf(buf, sizeof(buf), "[%s$%d]", show_special(comparison), param);
1627 return alloc_sname(buf);
1630 static char *get_return_compare_str(struct expression *expr)
1632 char *compare_str;
1634 compare_str = get_return_compare_is_param(expr);
1635 if (compare_str)
1636 return compare_str;
1638 compare_str = expr_lte_to_param(expr, -1);
1639 if (compare_str)
1640 return compare_str;
1642 return expr_param_comparison(expr, -1);
1645 static const char *get_return_ranges_str(struct expression *expr, struct range_list **rl_p)
1647 struct expression *fake;
1648 struct range_list *rl;
1649 const char *return_ranges;
1650 sval_t sval;
1651 const char *container_of_str;
1652 const char *math_str;
1653 char *fn_param_str;
1654 char *compare_str;
1655 char buf[128];
1657 *rl_p = NULL;
1659 if (!expr)
1660 return alloc_sname("");
1662 fake = get_fake_variable(expr);
1663 if (fake)
1664 expr = fake;
1666 container_of_str = get_container_of_str(expr);
1668 if (get_implied_value(expr, &sval)) {
1669 sval = sval_cast(cur_func_return_type(), sval);
1670 *rl_p = alloc_rl(sval, sval);
1671 return_ranges = sval_to_str_or_err_ptr(sval);
1672 if (container_of_str) {
1673 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1674 return alloc_sname(buf);
1676 return return_ranges;
1679 fn_param_str = get_fn_param_str(expr);
1680 math_str = get_param_key_swap_dollar(expr);
1681 compare_str = expr_equal_to_param(expr, -1);
1682 if (!math_str)
1683 math_str = get_value_in_terms_of_parameter_math(expr);
1685 if (get_implied_rl(expr, &rl) && !is_whole_rl(rl)) {
1686 rl = cast_rl(cur_func_return_type(), rl);
1687 return_ranges = show_rl(rl);
1688 } else if (get_imaginary_absolute(expr, &rl)){
1689 rl = cast_rl(cur_func_return_type(), rl);
1690 return alloc_sname(show_rl(rl));
1691 } else {
1692 get_absolute_rl(expr, &rl);
1693 rl = cast_rl(cur_func_return_type(), rl);
1694 return_ranges = show_rl(rl);
1696 *rl_p = rl;
1698 if (container_of_str) {
1699 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1700 return alloc_sname(buf);
1702 if (fn_param_str) {
1703 snprintf(buf, sizeof(buf), "%s%s", return_ranges, fn_param_str);
1704 return alloc_sname(buf);
1706 if (compare_str) {
1707 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1708 return alloc_sname(buf);
1710 if (math_str) {
1711 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, math_str);
1712 return alloc_sname(buf);
1714 compare_str = get_return_compare_str(expr);
1715 if (compare_str) {
1716 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1717 return alloc_sname(buf);
1720 return return_ranges;
1723 static void match_return_info(int return_id, char *return_ranges, struct expression *expr)
1725 sql_insert_return_states(return_id, return_ranges, INTERNAL, -1, "", function_signature());
1728 static bool call_return_state_hooks_conditional(struct expression *expr)
1730 int final_pass_orig = final_pass;
1731 static int recurse;
1733 if (recurse >= 2)
1734 return false;
1735 if (!expr ||
1736 (expr->type != EXPR_CONDITIONAL && expr->type != EXPR_SELECT))
1737 return false;
1739 recurse++;
1741 __push_fake_cur_stree();
1743 final_pass = 0;
1744 __split_whole_condition(expr->conditional);
1745 final_pass = final_pass_orig;
1747 call_return_state_hooks(expr->cond_true ?: expr->conditional);
1749 __push_true_states();
1750 __use_false_states();
1752 call_return_state_hooks(expr->cond_false);
1754 __merge_true_states();
1755 __free_fake_cur_stree();
1757 recurse--;
1758 return true;
1761 static bool handle_forced_split(const char *return_ranges, struct expression *expr)
1763 struct split_data *data = NULL;
1764 struct expression *compare;
1765 struct range_list *rl;
1766 char buf[64];
1767 char *math;
1768 sval_t sval;
1769 bool undo;
1770 int i;
1772 for (i = 0; i < split_count; i++) {
1773 if (get_function() &&
1774 strcmp(get_function(), forced_splits[i]->func) == 0) {
1775 data = forced_splits[i];
1776 break;
1779 if (!data)
1780 return false;
1782 // FIXME: this works for copy_to/from_user() because the only thing we
1783 // care about is zero/non-zero
1784 if (strcmp(data->rl, "0") != 0)
1785 return false;
1787 compare = compare_expression(expr, SPECIAL_EQUAL, zero_expr());
1788 if (!compare)
1789 return false;
1790 if (get_implied_value(compare, &sval))
1791 return false;
1793 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
1794 call_return_states_callbacks("0", expr);
1795 if (undo)
1796 end_assume();
1798 undo = assume(compare_expression(expr, SPECIAL_NOTEQUAL, zero_expr()));
1799 if (get_implied_rl(expr, &rl)) {
1800 math = strchr(return_ranges, '[');
1801 snprintf(buf, sizeof(buf), "%s%s", show_rl(rl), math ?: "");
1802 } else {
1803 snprintf(buf, sizeof(buf), "%s", return_ranges);
1805 call_return_states_callbacks(buf, expr);
1806 if (undo)
1807 end_assume();
1809 return true;
1812 static void call_return_states_callbacks(const char *return_ranges, struct expression *expr)
1814 struct returned_state_callback *cb;
1816 return_ranges = replace_return_ranges(return_ranges);
1817 if (is_delete_return(return_ranges))
1818 return;
1819 if (is_project_delete_return(expr))
1820 return;
1821 if (handle_forced_split(return_ranges, expr))
1822 return;
1824 return_id++;
1825 FOR_EACH_PTR(returned_state_callbacks, cb) {
1826 cb->callback(return_id, (char *)return_ranges, expr);
1827 } END_FOR_EACH_PTR(cb);
1830 static void call_return_state_hooks_compare(struct expression *expr)
1832 char *return_ranges;
1833 int final_pass_orig = final_pass;
1834 sval_t sval = { .type = &int_ctype };
1835 sval_t ret;
1837 if (!get_implied_value(expr, &ret))
1838 ret.value = -1;
1840 __push_fake_cur_stree();
1842 final_pass = 0;
1843 __split_whole_condition(expr);
1844 final_pass = final_pass_orig;
1846 if (ret.value != 0) {
1847 return_ranges = alloc_sname("1");
1848 sval.value = 1;
1849 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1851 call_return_states_callbacks(return_ranges, expr);
1854 __push_true_states();
1855 __use_false_states();
1857 if (ret.value != 1) {
1858 return_ranges = alloc_sname("0");
1859 sval.value = 0;
1860 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1862 call_return_states_callbacks(return_ranges, expr);
1865 __merge_true_states();
1866 __free_fake_cur_stree();
1869 static bool is_implies_function(struct expression *expr)
1871 struct range_list *rl;
1873 if (!expr)
1874 return false;
1876 rl = get_range_implications(get_function());
1877 if (!rl)
1878 return false;
1880 sm_msg("%s: is implied", __func__);
1881 return true;
1884 static int ptr_in_list(struct sm_state *sm, struct state_list *slist)
1886 struct sm_state *tmp;
1888 FOR_EACH_PTR(slist, tmp) {
1889 if (strcmp(tmp->state->name, sm->state->name) == 0)
1890 return 1;
1891 } END_FOR_EACH_PTR(tmp);
1893 return 0;
1896 static int split_possible_helper(struct sm_state *sm, struct expression *expr)
1898 struct range_list *rl;
1899 char *return_ranges;
1900 struct sm_state *tmp;
1901 int ret = 0;
1902 int nr_possible, nr_states;
1903 char *compare_str;
1904 char buf[128];
1905 struct state_list *already_handled = NULL;
1906 sval_t sval;
1908 if (!sm || !sm->merged)
1909 return 0;
1911 if (too_many_possible(sm) && !is_implies_function(expr))
1912 return 0;
1914 /* bail if it gets too complicated */
1915 nr_possible = 0;
1916 FOR_EACH_PTR(sm->possible, tmp) {
1917 if (tmp->merged)
1918 continue;
1919 if (ptr_in_list(tmp, already_handled))
1920 continue;
1921 add_ptr_list(&already_handled, tmp);
1922 nr_possible++;
1923 } END_FOR_EACH_PTR(tmp);
1924 free_slist(&already_handled);
1925 nr_states = get_db_state_count();
1926 if (nr_states * nr_possible >= 2000 && !is_implies_function(expr))
1927 return 0;
1929 FOR_EACH_PTR(sm->possible, tmp) {
1930 if (!is_leaf(tmp))
1931 continue;
1932 if (ptr_in_list(tmp, already_handled))
1933 continue;
1934 add_ptr_list(&already_handled, tmp);
1936 ret = 1;
1937 __push_fake_cur_stree();
1939 overwrite_states_using_pool(sm, tmp);
1941 rl = cast_rl(cur_func_return_type(), estate_rl(tmp->state));
1942 return_ranges = show_rl(rl);
1943 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(clone_rl(rl)));
1944 compare_str = get_return_compare_str(expr);
1945 /* ignore obvious stuff like 0 <= param */
1946 /* Is this worthile when we have PARAM_COMPARE? */
1947 if (compare_str &&
1948 strncmp(compare_str, "[=", 2) != 0 &&
1949 rl_to_sval(rl, &sval))
1950 compare_str = NULL;
1951 if (compare_str) {
1952 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1953 return_ranges = alloc_sname(buf);
1956 call_return_states_callbacks(return_ranges, expr);
1958 __free_fake_cur_stree();
1959 } END_FOR_EACH_PTR(tmp);
1961 free_slist(&already_handled);
1963 return ret;
1966 static int call_return_state_hooks_split_possible(struct expression *expr)
1968 struct sm_state *sm;
1970 if (!expr)
1971 return 0;
1973 sm = get_returned_sm(expr);
1974 return split_possible_helper(sm, expr);
1977 static bool has_empty_state(struct sm_state *sm)
1979 struct sm_state *tmp;
1981 FOR_EACH_PTR(sm->possible, tmp) {
1982 if (!estate_rl(tmp->state))
1983 return true;
1984 } END_FOR_EACH_PTR(tmp);
1986 return false;
1989 static bool has_possible_negative(struct sm_state *sm)
1991 struct sm_state *tmp;
1993 if (!type_signed(estate_type(sm->state)))
1994 return false;
1996 FOR_EACH_PTR(sm->possible, tmp) {
1997 if (!estate_rl(tmp->state))
1998 continue;
1999 if (sval_is_negative(estate_min(tmp->state)) &&
2000 sval_is_negative(estate_max(tmp->state)))
2001 return true;
2002 } END_FOR_EACH_PTR(tmp);
2004 return false;
2007 static bool has_separate_zero_null(struct sm_state *sm)
2009 struct sm_state *tmp;
2010 sval_t sval;
2012 FOR_EACH_PTR(sm->possible, tmp) {
2013 if (!estate_get_single_value(tmp->state, &sval))
2014 continue;
2015 if (sval.value == 0)
2016 return true;
2017 } END_FOR_EACH_PTR(tmp);
2019 return false;
2022 static int split_positive_from_negative(struct expression *expr)
2024 struct sm_state *sm;
2025 struct range_list *rl;
2026 const char *return_ranges;
2027 struct range_list *ret_rl;
2028 bool separate_zero;
2029 int undo;
2031 /* We're going to print the states 3 times */
2032 if (get_db_state_count() > 10000 / 3)
2033 return 0;
2035 if (!get_implied_rl(expr, &rl) || !rl)
2036 return 0;
2037 /* Forget about INT_MAX and larger */
2038 if (rl_max(rl).value <= 0)
2039 return 0;
2040 if (!sval_is_negative(rl_min(rl)))
2041 return 0;
2043 sm = get_returned_sm(expr);
2044 if (!sm)
2045 return 0;
2046 if (has_empty_state(sm))
2047 return 0;
2048 if (!has_possible_negative(sm))
2049 return 0;
2050 separate_zero = has_separate_zero_null(sm);
2052 if (!assume(compare_expression(expr, separate_zero ? '>' : SPECIAL_GTE, zero_expr())))
2053 return 0;
2055 return_ranges = get_return_ranges_str(expr, &ret_rl);
2056 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2057 call_return_states_callbacks(return_ranges, expr);
2059 end_assume();
2061 if (separate_zero) {
2062 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
2064 return_ranges = get_return_ranges_str(expr, &ret_rl);
2065 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2066 call_return_states_callbacks(return_ranges, expr);
2068 if (undo)
2069 end_assume();
2072 undo = assume(compare_expression(expr, '<', zero_expr()));
2074 return_ranges = get_return_ranges_str(expr, &ret_rl);
2075 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2076 call_return_states_callbacks(return_ranges, expr);
2078 if (undo)
2079 end_assume();
2081 return 1;
2084 static int call_return_state_hooks_split_null_non_null_zero(struct expression *expr)
2086 struct range_list *rl;
2087 struct range_list *nonnull_rl;
2088 sval_t null_sval;
2089 struct range_list *null_rl = NULL;
2090 char *return_ranges;
2091 struct sm_state *sm;
2092 struct smatch_state *state;
2093 int nr_states;
2094 int final_pass_orig = final_pass;
2096 if (!expr || expr_equal_to_param(expr, -1))
2097 return 0;
2098 if (expr->type == EXPR_CALL)
2099 return 0;
2101 sm = get_returned_sm(expr);
2102 if (!sm)
2103 return 0;
2104 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2105 return 0;
2106 state = sm->state;
2107 if (!estate_rl(state))
2108 return 0;
2109 if (estate_min(state).value == 0 && estate_max(state).value == 0)
2110 return 0;
2111 if (has_possible_negative(sm))
2112 return 0;
2113 if (!has_separate_zero_null(sm))
2114 return 0;
2116 nr_states = get_db_state_count();
2117 if (option_info && nr_states >= 1500)
2118 return 0;
2120 rl = estate_rl(state);
2122 __push_fake_cur_stree();
2124 final_pass = 0;
2125 __split_whole_condition(expr);
2126 final_pass = final_pass_orig;
2128 nonnull_rl = rl_filter(rl, rl_zero());
2129 return_ranges = show_rl(nonnull_rl);
2130 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonnull_rl));
2132 call_return_states_callbacks(return_ranges, expr);
2134 __push_true_states();
2135 __use_false_states();
2137 return_ranges = alloc_sname("0");
2138 null_sval = sval_type_val(rl_type(rl), 0);
2139 add_range(&null_rl, null_sval, null_sval);
2140 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(null_rl));
2141 call_return_states_callbacks(return_ranges, expr);
2143 __merge_true_states();
2144 __free_fake_cur_stree();
2146 return 1;
2149 static bool is_neg_and_pos_err_code(struct range_list *rl)
2151 struct data_range *tmp, *last;
2153 if (option_project != PROJ_KERNEL)
2154 return false;
2155 if (!rl)
2156 return false;
2158 /* Assume s32min-(14),(-12)-(-1),1-s32max is an error code. */
2159 last = last_ptr_list((struct ptr_list *)rl);
2160 if (last->max.value >= 0 &&
2161 (last->min.value != 1 ||
2162 last->max.value != INT_MAX))
2163 return false;
2166 FOR_EACH_PTR(rl, tmp) {
2167 if (tmp == last)
2168 break;
2169 if (tmp->min.value != INT_MIN && tmp->min.value < -4095)
2170 return false;
2171 if (tmp->max.value < -4095 || tmp->max.value >= 0)
2172 return false;
2173 } END_FOR_EACH_PTR(tmp);
2175 return true;
2178 static bool is_kernel_success_fail(struct sm_state *sm)
2180 struct sm_state *tmp;
2181 struct range_list *rl;
2182 bool has_zero = false;
2183 bool has_neg = false;
2185 if (!sm)
2186 return false;
2188 if (!type_signed(estate_type(sm->state)))
2189 return false;
2191 FOR_EACH_PTR(sm->possible, tmp) {
2192 rl = estate_rl(tmp->state);
2193 if (!rl)
2194 return false;
2195 if (!is_leaf(tmp))
2196 continue;
2197 if (rl_min(rl).value == 0 && rl_max(rl).value == 0) {
2198 has_zero = true;
2199 continue;
2201 has_neg = true;
2202 if (is_neg_and_pos_err_code(estate_rl(tmp->state)))
2203 continue;
2204 return false;
2205 } END_FOR_EACH_PTR(tmp);
2207 return has_zero && has_neg;
2210 static int call_return_state_hooks_split_success_fail(struct expression *expr)
2212 struct expression *tmp_ret;
2213 struct sm_state *sm;
2214 struct range_list *rl;
2215 struct range_list *nonzero_rl;
2216 sval_t zero_sval;
2217 struct range_list *zero_rl = NULL;
2218 int nr_states;
2219 char *return_ranges;
2220 int final_pass_orig = final_pass;
2222 if (option_project != PROJ_KERNEL)
2223 return 0;
2225 nr_states = get_db_state_count();
2226 if (nr_states > 2000)
2227 return 0;
2229 tmp_ret = get_fake_variable(expr);
2230 if (!tmp_ret)
2231 tmp_ret = expr;
2232 sm = get_returned_sm(tmp_ret);
2233 if (!sm)
2234 return 0;
2235 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2236 return 0;
2237 if (!is_kernel_success_fail(sm))
2238 return 0;
2240 rl = estate_rl(sm->state);
2241 if (!rl)
2242 return 0;
2244 __push_fake_cur_stree();
2246 final_pass = 0;
2247 __split_whole_condition(tmp_ret);
2248 final_pass = final_pass_orig;
2250 nonzero_rl = rl_filter(rl, rl_zero());
2251 nonzero_rl = cast_rl(cur_func_return_type(), nonzero_rl);
2252 return_ranges = show_rl(nonzero_rl);
2253 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonzero_rl));
2255 call_return_states_callbacks(return_ranges, expr);
2257 __push_true_states();
2258 __use_false_states();
2260 return_ranges = alloc_sname("0");
2261 zero_sval = sval_type_val(rl_type(rl), 0);
2262 add_range(&zero_rl, zero_sval, zero_sval);
2263 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(zero_rl));
2264 call_return_states_callbacks(return_ranges, expr);
2266 __merge_true_states();
2267 __free_fake_cur_stree();
2269 return 1;
2272 static int is_boolean(struct expression *expr)
2274 struct range_list *rl;
2276 if (!get_implied_rl(expr, &rl))
2277 return 0;
2278 if (rl_min(rl).value == 0 && rl_max(rl).value == 1)
2279 return 1;
2280 return 0;
2283 static int splitable_function_call(struct expression *expr)
2285 struct sm_state *sm;
2287 if (!expr || expr->type != EXPR_CALL)
2288 return 0;
2289 sm = get_extra_sm_state(expr);
2290 return split_possible_helper(sm, expr);
2293 static struct sm_state *find_bool_param(void)
2295 struct stree *start_states;
2296 struct symbol *arg;
2297 struct sm_state *sm, *tmp;
2298 sval_t sval;
2300 start_states = get_start_states();
2302 FOR_EACH_PTR_REVERSE(cur_func_sym->ctype.base_type->arguments, arg) {
2303 if (!arg->ident)
2304 continue;
2305 sm = get_sm_state_stree(start_states, SMATCH_EXTRA, arg->ident->name, arg);
2306 if (!sm)
2307 continue;
2308 if (rl_min(estate_rl(sm->state)).value != 0 ||
2309 rl_max(estate_rl(sm->state)).value != 1)
2310 continue;
2311 goto found;
2312 } END_FOR_EACH_PTR_REVERSE(arg);
2314 return NULL;
2316 found:
2318 * Check if it's splitable. If not, then splitting it up is likely not
2319 * useful for the callers.
2321 FOR_EACH_PTR(sm->possible, tmp) {
2322 if (is_merged(tmp))
2323 continue;
2324 if (!estate_get_single_value(tmp->state, &sval))
2325 return NULL;
2326 } END_FOR_EACH_PTR(tmp);
2328 return sm;
2331 static int split_on_bool_sm(struct sm_state *sm, struct expression *expr)
2333 struct range_list *ret_rl;
2334 const char *return_ranges;
2335 struct sm_state *tmp;
2336 int ret = 0;
2337 struct state_list *already_handled = NULL;
2339 if (!sm || !sm->merged)
2340 return 0;
2342 if (too_many_possible(sm))
2343 return 0;
2345 FOR_EACH_PTR(sm->possible, tmp) {
2346 if (tmp->merged)
2347 continue;
2348 if (ptr_in_list(tmp, already_handled))
2349 continue;
2350 add_ptr_list(&already_handled, tmp);
2352 ret = 1;
2353 __push_fake_cur_stree();
2355 overwrite_states_using_pool(sm, tmp);
2357 return_ranges = get_return_ranges_str(expr, &ret_rl);
2358 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2359 call_return_states_callbacks(return_ranges, expr);
2361 __free_fake_cur_stree();
2362 } END_FOR_EACH_PTR(tmp);
2364 free_slist(&already_handled);
2366 return ret;
2369 static int split_by_bool_param(struct expression *expr)
2371 struct sm_state *start_sm, *sm;
2372 sval_t sval;
2374 start_sm = find_bool_param();
2375 if (!start_sm)
2376 return 0;
2377 sm = get_sm_state(SMATCH_EXTRA, start_sm->name, start_sm->sym);
2378 if (!sm || estate_get_single_value(sm->state, &sval))
2379 return 0;
2381 if (get_db_state_count() * 2 >= 2000)
2382 return 0;
2384 return split_on_bool_sm(sm, expr);
2387 static int split_by_null_nonnull_param(struct expression *expr)
2389 struct symbol *arg;
2390 struct sm_state *sm;
2391 int nr_possible;
2393 arg = first_ptr_list((struct ptr_list *)cur_func_sym->ctype.base_type->arguments);
2394 if (!arg || !arg->ident)
2395 return 0;
2396 if (get_real_base_type(arg)->type != SYM_PTR)
2397 return 0;
2399 if (param_was_set_var_sym(arg->ident->name, arg))
2400 return 0;
2401 sm = get_sm_state(SMATCH_EXTRA, arg->ident->name, arg);
2402 if (!sm)
2403 return 0;
2405 if (!has_separate_zero_null(sm))
2406 return 0;
2408 nr_possible = ptr_list_size((struct ptr_list *)sm->possible);
2409 if (get_db_state_count() * nr_possible >= 2000)
2410 return 0;
2412 return split_on_bool_sm(sm, expr);
2415 static void call_hooks_based_on_pool(struct expression *expr, struct sm_state *gate_sm, struct sm_state *pool_sm)
2417 struct range_list *ret_rl;
2418 const char *return_ranges;
2420 __push_fake_cur_stree();
2422 overwrite_states_using_pool(gate_sm, pool_sm);
2424 return_ranges = get_return_ranges_str(expr, &ret_rl);
2425 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2426 call_return_states_callbacks(return_ranges, expr);
2428 __free_fake_cur_stree();
2431 static bool split_by_impossible(struct expression *expr)
2433 static int impossible_id;
2434 struct sm_state *sm, *tmp;
2435 int nr_states;
2437 if (!impossible_id)
2438 impossible_id = id_from_name("register_impossible_return");
2439 if (!impossible_id)
2440 return false;
2443 * The only states for register_impossible_return are &impossible,
2444 * &undefined and &merged. This function will break otherwise.
2447 sm = get_sm_state(impossible_id, "impossible", NULL);
2448 if (!sm || sm->state != &merged)
2449 return false;
2451 nr_states = get_db_state_count();
2452 if (nr_states >= 1000)
2453 return false;
2455 /* handle possible */
2456 FOR_EACH_PTR(sm->possible, tmp) {
2457 if (!is_leaf(tmp))
2458 continue;
2459 if (tmp->state != &undefined)
2460 continue;
2461 call_hooks_based_on_pool(expr, sm, tmp);
2462 goto impossible;
2463 } END_FOR_EACH_PTR(tmp);
2465 impossible:
2466 /* handle impossible */
2467 FOR_EACH_PTR(sm->possible, tmp) {
2468 if (!is_leaf(tmp))
2469 continue;
2470 if (strcmp(tmp->state->name, "impossible") != 0)
2471 continue;
2472 call_hooks_based_on_pool(expr, sm, tmp);
2473 return true;
2474 } END_FOR_EACH_PTR(tmp);
2476 return false;
2479 struct expression *strip_expr_statement(struct expression *expr)
2481 struct expression *orig = expr;
2482 struct statement *stmt, *last_stmt;
2484 if (!expr)
2485 return NULL;
2486 if (expr->type == EXPR_PREOP && expr->op == '(')
2487 expr = expr->unop;
2488 if (expr->type != EXPR_STATEMENT)
2489 return orig;
2490 stmt = expr->statement;
2491 if (!stmt || stmt->type != STMT_COMPOUND)
2492 return orig;
2494 last_stmt = last_ptr_list((struct ptr_list *)stmt->stmts);
2495 if (!last_stmt || last_stmt->type == STMT_LABEL)
2496 last_stmt = last_stmt->label_statement;
2497 if (!last_stmt || last_stmt->type != STMT_EXPRESSION)
2498 return orig;
2499 return strip_expr(last_stmt->expression);
2502 static bool is_kernel_error_path(struct expression *expr)
2504 struct range_list *rl;
2506 if (option_project != PROJ_KERNEL)
2507 return false;
2509 if (!get_implied_rl(expr, &rl))
2510 return false;
2511 if (rl_type(rl) != &int_ctype)
2512 return false;
2513 if (!is_neg_and_pos_err_code(rl))
2514 return false;
2515 return true;
2518 static void call_return_state_hooks(struct expression *expr)
2520 struct range_list *ret_rl;
2521 const char *return_ranges;
2522 int nr_states;
2523 sval_t sval;
2525 if (debug_db) {
2526 struct range_list *rl = NULL;
2528 get_absolute_rl(expr, &rl);
2529 sm_msg("RETURN: expr='%s' rl='%s' %lu states%s", expr_to_str(expr),
2530 show_rl(rl), stree_count(__get_cur_stree()),
2531 is_impossible_path() ? " (impossible path)" : "");
2534 if (__path_is_null())
2535 return;
2537 if (is_impossible_path())
2538 goto vanilla;
2540 if (expr && (expr->type == EXPR_COMPARE ||
2541 !get_implied_value(expr, &sval)) &&
2542 (is_condition(expr) || is_boolean(expr))) {
2543 call_return_state_hooks_compare(expr);
2544 if (debug_db)
2545 sm_msg("%s: bool", __func__);
2546 return;
2547 } else if (call_return_state_hooks_conditional(expr)) {
2548 if (debug_db)
2549 sm_msg("%s: condition", __func__);
2550 return;
2551 } else if (is_kernel_error_path(expr)) {
2552 if (debug_db)
2553 sm_msg("%s: kernel error path", __func__);
2554 goto vanilla;
2555 } else if (call_return_state_hooks_split_success_fail(expr)) {
2556 if (debug_db)
2557 sm_msg("%s: success_fail", __func__);
2558 return;
2559 } else if (call_return_state_hooks_split_possible(expr)) {
2560 if (debug_db)
2561 sm_msg("%s: split_possible", __func__);
2562 return;
2563 } else if (split_positive_from_negative(expr)) {
2564 if (debug_db)
2565 sm_msg("%s: positive negative", __func__);
2566 return;
2567 } else if (call_return_state_hooks_split_null_non_null_zero(expr)) {
2568 if (debug_db)
2569 sm_msg("%s: split zero non-zero", __func__);
2570 return;
2571 } else if (splitable_function_call(expr)) {
2572 if (debug_db)
2573 sm_msg("%s: split_function_call", __func__);
2574 return;
2575 } else if (split_by_bool_param(expr)) {
2576 if (debug_db)
2577 sm_msg("%s: bool param", __func__);
2578 return;
2579 } else if (split_by_null_nonnull_param(expr)) {
2580 if (debug_db)
2581 sm_msg("%s: null non-null param", __func__);
2582 return;
2583 } else if (split_by_impossible(expr)) {
2584 if (debug_db)
2585 sm_msg("%s: split by impossible", __func__);
2586 return;
2589 vanilla:
2590 return_ranges = get_return_ranges_str(expr, &ret_rl);
2591 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2593 nr_states = get_db_state_count();
2594 if (nr_states >= 10000) {
2595 return_id++;
2596 match_return_info(return_id, (char *)return_ranges, expr);
2597 print_limited_param_set(return_id, (char *)return_ranges, expr);
2598 mark_all_params_untracked(return_id, (char *)return_ranges, expr);
2599 return;
2601 call_return_states_callbacks(return_ranges, expr);
2602 if (debug_db)
2603 sm_msg("%s: vanilla", __func__);
2606 static void print_returned_struct_members(int return_id, char *return_ranges, struct expression *expr)
2608 struct returned_member_callback *cb;
2609 struct sm_state *sm;
2610 struct symbol *type;
2611 char *name;
2612 char member_name[256];
2613 int len;
2615 type = get_type(expr);
2616 if (!type || type->type != SYM_PTR)
2617 return;
2618 name = expr_to_var(expr);
2619 if (!name)
2620 return;
2622 len = strlen(name);
2623 FOR_EACH_PTR(returned_member_callbacks, cb) {
2624 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2625 if (sm->name[0] == '*' && strcmp(sm->name + 1, name) == 0) {
2626 strcpy(member_name, "*$");
2627 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2628 continue;
2630 if (strncmp(sm->name, name, len) != 0)
2631 continue;
2632 if (strncmp(sm->name + len, "->", 2) != 0)
2633 continue;
2634 snprintf(member_name, sizeof(member_name), "$%s", sm->name + len);
2635 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2636 } END_FOR_EACH_SM(sm);
2637 } END_FOR_EACH_PTR(cb);
2639 free_string(name);
2642 static void print_return_struct_info(int return_id, char *return_ranges,
2643 struct expression *expr,
2644 struct symbol *sym,
2645 struct return_info_callback *cb)
2647 struct sm_state *sm;
2648 const char *printed_name;
2649 int param;
2651 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2652 param = get_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2653 if (!printed_name)
2654 continue;
2655 if (param < 0)
2656 continue;
2657 cb->callback(return_id, return_ranges, expr, param, printed_name, sm);
2658 } END_FOR_EACH_SM(sm);
2660 /* always print returned states after processing param states */
2661 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2662 param = get_return_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2663 if (param != -1 || !printed_name)
2664 continue;
2665 cb->callback(return_id, return_ranges, expr, -1, printed_name, sm);
2666 } END_FOR_EACH_SM(sm);
2669 static void print_return_info(int return_id, char *return_ranges, struct expression *expr)
2671 struct return_info_callback *cb;
2672 struct expression *tmp;
2673 struct symbol *sym;
2675 if (!option_info && !__inline_fn &&
2676 !local_debug && !option_debug)
2677 return;
2679 tmp = get_fake_variable(expr);
2680 if (tmp)
2681 expr = tmp;
2682 sym = expr_to_sym(expr);
2684 FOR_EACH_PTR(return_callbacks, cb) {
2685 __ignore_param_used++;
2686 print_return_struct_info(return_id, return_ranges, expr, sym, cb);
2687 __ignore_param_used--;
2688 } END_FOR_EACH_PTR(cb);
2691 static void reset_memdb(struct symbol *sym)
2693 mem_sql(NULL, NULL, "delete from caller_info;");
2694 mem_sql(NULL, NULL, "delete from return_states;");
2695 mem_sql(NULL, NULL, "delete from call_implies;");
2696 mem_sql(NULL, NULL, "delete from return_implies;");
2699 static void match_end_func_info(struct symbol *sym)
2701 if (__path_is_null())
2702 return;
2703 call_return_state_hooks(NULL);
2706 static void match_after_func(struct symbol *sym)
2708 clear_cached_return_vals();
2709 if (!__inline_fn)
2710 reset_memdb(sym);
2713 static void init_memdb(void)
2715 char *err = NULL;
2716 int rc;
2717 const char *schema_files[] = {
2718 "db/db.schema",
2719 "db/caller_info.schema",
2720 "db/common_caller_info.schema",
2721 "db/return_states.schema",
2722 "db/function_type_size.schema",
2723 "db/type_size.schema",
2724 "db/function_type_info.schema",
2725 "db/type_info.schema",
2726 "db/call_implies.schema",
2727 "db/return_implies.schema",
2728 "db/function_ptr.schema",
2729 "db/local_values.schema",
2730 "db/function_type_value.schema",
2731 "db/type_value.schema",
2732 "db/function_type.schema",
2733 "db/data_info.schema",
2734 "db/parameter_name.schema",
2735 "db/constraints.schema",
2736 "db/constraints_required.schema",
2737 "db/fn_ptr_data_link.schema",
2738 "db/fn_data_link.schema",
2739 "db/mtag_about.schema",
2740 "db/mtag_info.schema",
2741 "db/mtag_map.schema",
2742 "db/mtag_data.schema",
2743 "db/mtag_alias.schema",
2745 static char buf[4096];
2746 int fd;
2747 int ret;
2748 int i;
2750 rc = sqlite3_open(":memory:", &mem_db);
2751 if (rc != SQLITE_OK) {
2752 sm_ierror("starting In-Memory database.");
2753 return;
2756 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2757 fd = open_schema_file(schema_files[i]);
2758 if (fd < 0)
2759 continue;
2760 ret = read(fd, buf, sizeof(buf));
2761 if (ret < 0) {
2762 sm_ierror("failed to read: %s", schema_files[i]);
2763 continue;
2765 close(fd);
2766 if (ret == sizeof(buf)) {
2767 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2768 schema_files[i], sizeof(buf));
2769 continue;
2771 buf[ret] = '\0';
2772 rc = sqlite3_exec(mem_db, buf, NULL, NULL, &err);
2773 if (rc != SQLITE_OK) {
2774 sm_ierror("SQL error #2: %s", err);
2775 sm_ierror("%s", buf);
2780 static void init_cachedb(void)
2782 char *err = NULL;
2783 int rc;
2784 const char *schema_files[] = {
2785 "db/call_implies.schema",
2786 "db/return_implies.schema",
2787 "db/type_info.schema",
2788 "db/mtag_about.schema",
2789 "db/mtag_data.schema",
2790 "db/mtag_info.schema",
2791 "db/sink_info.schema",
2792 "db/hash_string.schema",
2794 static char buf[4096];
2795 int fd;
2796 int ret;
2797 int i;
2799 rc = sqlite3_open(":memory:", &cache_db);
2800 if (rc != SQLITE_OK) {
2801 sm_ierror("starting In-Memory database.");
2802 return;
2805 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2806 fd = open_schema_file(schema_files[i]);
2807 if (fd < 0)
2808 continue;
2809 ret = read(fd, buf, sizeof(buf));
2810 if (ret < 0) {
2811 sm_ierror("failed to read: %s", schema_files[i]);
2812 continue;
2814 close(fd);
2815 if (ret == sizeof(buf)) {
2816 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2817 schema_files[i], sizeof(buf));
2818 continue;
2820 buf[ret] = '\0';
2821 rc = sqlite3_exec(cache_db, buf, NULL, NULL, &err);
2822 if (rc != SQLITE_OK) {
2823 sm_ierror("SQL error #2: %s", err);
2824 sm_ierror("%s", buf);
2829 static int save_cache_data(void *_table, int argc, char **argv, char **azColName)
2831 static char buf[4096];
2832 char tmp[256];
2833 char *p = buf;
2834 char *table = _table;
2835 int i;
2838 p += snprintf(p, 4096 - (p - buf), "insert or ignore into %s values (", table);
2839 for (i = 0; i < argc; i++) {
2840 if (i)
2841 p += snprintf(p, 4096 - (p - buf), ", ");
2842 sqlite3_snprintf(sizeof(tmp), tmp, "%q", escape_newlines(argv[i]));
2843 p += snprintf(p, 4096 - (p - buf), "'%s'", tmp);
2846 p += snprintf(p, 4096 - (p - buf), ");");
2847 if (p - buf > 4096)
2848 return 0;
2850 sm_msg("SQL: %s", buf);
2851 return 0;
2854 static void dump_cache(struct symbol_list *sym_list)
2856 const char *cache_tables[] = {
2857 "type_info", "return_implies", "call_implies", "mtag_data",
2858 "mtag_info", "mtag_about", "sink_info", "hash_string",
2860 char buf[64];
2861 int i;
2863 if (!option_info)
2864 return;
2866 for (i = 0; i < ARRAY_SIZE(cache_tables); i++) {
2867 snprintf(buf, sizeof(buf), "select * from %s;", cache_tables[i]);
2868 cache_sql(&save_cache_data, (char *)cache_tables[i], buf);
2872 void open_smatch_db(char *db_file)
2874 int rc;
2876 if (option_no_db)
2877 return;
2879 use_states = malloc(num_checks);
2880 memset(use_states, 0xff, num_checks);
2882 init_memdb();
2883 init_cachedb();
2885 rc = sqlite3_open_v2(db_file, &smatch_db, SQLITE_OPEN_READONLY, NULL);
2886 if (rc != SQLITE_OK) {
2887 option_no_db = 1;
2888 return;
2890 run_sql(NULL, NULL,
2891 "PRAGMA cache_size = %d;", SQLITE_CACHE_PAGES);
2892 return;
2895 static char *get_next_string(char **str)
2897 static char string[256];
2898 char *start;
2899 char *p = *str;
2900 int len, i, j;
2902 if (*p == '\0')
2903 return NULL;
2904 start = p;
2906 while (*p != '\0' && *p != '\n') {
2907 if (*p == '\\' && *(p + 1) == ' ') {
2908 p += 2;
2909 continue;
2911 if (*p == ' ')
2912 break;
2913 p++;
2916 len = p - start;
2917 if (len >= sizeof(string)) {
2918 memcpy(string, start, sizeof(string));
2919 string[sizeof(string) - 1] = '\0';
2920 sm_ierror("return_fix: '%s' too long", string);
2921 **str = '\0';
2922 return NULL;
2924 memcpy(string, start, len);
2925 string[len] = '\0';
2926 for (i = 0; i < sizeof(string) - 1; i++) {
2927 if (string[i] == '\\' && string[i + 1] == ' ') {
2928 for (j = i; string[j] != '\0'; j++)
2929 string[j] = string[j + 1];
2932 if (*p != '\0')
2933 p++;
2934 *str = p;
2935 return string;
2938 static void register_return_deletes(void)
2940 char *func, *ret_str;
2941 char filename[256];
2942 char buf[4096];
2943 int fd, ret, i;
2944 char *p;
2946 snprintf(filename, 256, "db/%s.delete.return_states", option_project_str);
2947 fd = open_schema_file(filename);
2948 if (fd < 0)
2949 return;
2950 ret = read(fd, buf, sizeof(buf));
2951 close(fd);
2952 if (ret < 0)
2953 return;
2954 if (ret == sizeof(buf)) {
2955 sm_ierror("file too large: %s (limit %zd bytes)",
2956 filename, sizeof(buf));
2957 return;
2959 buf[ret] = '\0';
2961 p = buf;
2962 while (*p) {
2963 get_next_string(&p);
2964 delete_count++;
2966 if (delete_count == 0)
2967 return;
2968 if (delete_count % 2 != 0) {
2969 printf("error parsing '%s' delete_count=%d\n", filename, delete_count);
2970 delete_count = 0;
2971 return;
2973 delete_table = malloc(delete_count * sizeof(char *));
2975 p = buf;
2976 i = 0;
2977 while (*p) {
2978 func = alloc_string(get_next_string(&p));
2979 ret_str = alloc_string(get_next_string(&p));
2981 delete_table[i++] = func;
2982 delete_table[i++] = ret_str;
2986 #define RETURN_FIX_SIZE 8196
2987 static void register_return_replacements(void)
2989 char *func, *orig, *new;
2990 char filename[256];
2991 int fd, ret, i;
2992 char *buf;
2993 char *p;
2995 snprintf(filename, 256, "db/%s.return_fixes", option_project_str);
2996 fd = open_schema_file(filename);
2997 if (fd < 0)
2998 return;
2999 buf = malloc(RETURN_FIX_SIZE);
3000 ret = read(fd, buf, RETURN_FIX_SIZE);
3001 close(fd);
3002 if (ret < 0) {
3003 free(buf);
3004 return;
3006 if (ret == RETURN_FIX_SIZE) {
3007 sm_ierror("file too large: %s (limit %d bytes)",
3008 filename, RETURN_FIX_SIZE);
3009 free(buf);
3010 return;
3012 buf[ret] = '\0';
3014 p = buf;
3015 while (*p) {
3016 get_next_string(&p);
3017 replace_count++;
3019 if (replace_count == 0) {
3020 free(buf);
3021 return;
3023 if (replace_count % 3 != 0) {
3024 printf("error parsing '%s' replace_count=%d\n", filename, replace_count);
3025 replace_count = 0;
3026 free(buf);
3027 return;
3029 replace_table = malloc(replace_count * sizeof(char *));
3031 p = buf;
3032 i = 0;
3033 while (*p) {
3034 func = alloc_string(get_next_string(&p));
3035 orig = alloc_string(get_next_string(&p));
3036 new = alloc_string(get_next_string(&p));
3038 replace_table[i++] = func;
3039 replace_table[i++] = orig;
3040 replace_table[i++] = new;
3042 free(buf);
3045 static void register_forced_return_splits(void)
3047 int struct_members = sizeof(struct split_data) / sizeof(char *);
3048 char filename[256];
3049 char buf[4096];
3050 int fd, ret, i;
3051 char *p;
3053 snprintf(filename, 256, "db/%s.forced_return_splits", option_project_str);
3054 fd = open_schema_file(filename);
3055 if (fd < 0)
3056 return;
3057 ret = read(fd, buf, sizeof(buf));
3058 close(fd);
3059 if (ret < 0)
3060 return;
3061 if (ret == sizeof(buf)) {
3062 sm_ierror("file too large: %s (limit %zd bytes)",
3063 filename, sizeof(buf));
3064 return;
3066 buf[ret] = '\0';
3068 p = buf;
3069 while (*p) {
3070 get_next_string(&p);
3071 split_count++;
3073 if (split_count == 0)
3074 return;
3075 if (split_count % struct_members != 0) {
3076 printf("error parsing '%s' split_count=%d\n", filename, split_count);
3077 split_count = 0;
3078 return;
3080 split_count /= struct_members;
3081 forced_splits = malloc(split_count * sizeof(void *));
3083 p = buf;
3084 i = 0;
3085 while (*p) {
3086 struct split_data *split = malloc(sizeof(*split));
3088 split->func = alloc_string(get_next_string(&p));
3089 split->rl = alloc_string(get_next_string(&p));
3090 forced_splits[i++] = split;
3094 void register_definition_db_callbacks(int id)
3096 my_id = id;
3098 add_hook(&match_call_info, FUNCTION_CALL_HOOK_BEFORE);
3099 add_hook(&match_call_info_new, FUNCTION_CALL_HOOK_BEFORE);
3100 add_split_return_callback(match_return_info);
3101 add_split_return_callback(print_returned_struct_members);
3102 add_split_return_callback(print_return_info);
3103 add_hook(&call_return_state_hooks, RETURN_HOOK);
3104 add_hook(&match_end_func_info, END_FUNC_HOOK);
3105 add_hook(&match_after_func, AFTER_FUNC_HOOK);
3107 add_hook(&match_data_from_db, FUNC_DEF_HOOK);
3108 add_hook(&match_call_implies, FUNC_DEF_HOOK);
3109 add_hook(&match_return_implies_early, CALL_HOOK_AFTER_INLINE);
3111 common_funcs = load_strings_from_file(option_project_str, "common_functions");
3112 register_return_deletes();
3113 register_return_replacements();
3114 register_forced_return_splits();
3116 add_hook(&dump_cache, END_FILE_HOOK);
3119 void register_definition_db_callbacks_late(int id)
3121 add_hook(&match_return_implies_late, CALL_HOOK_AFTER_INLINE);
3124 void register_db_call_marker(int id)
3126 add_hook(&match_call_marker, FUNCTION_CALL_HOOK_BEFORE);
3129 char *get_data_info_name(struct expression *expr)
3131 struct symbol *sym;
3132 char *name;
3133 char buf[256];
3134 char *ret = NULL;
3136 expr = strip_expr(expr);
3137 name = get_member_name(expr);
3138 if (name)
3139 return name;
3140 name = expr_to_var_sym(expr, &sym);
3141 if (!name || !sym)
3142 goto free;
3143 if (!(sym->ctype.modifiers & MOD_TOPLEVEL))
3144 goto free;
3145 if (sym->ctype.modifiers & MOD_STATIC)
3146 snprintf(buf, sizeof(buf), "static %s", name);
3147 else
3148 snprintf(buf, sizeof(buf), "global %s", name);
3149 ret = alloc_sname(buf);
3150 free:
3151 free_string(name);
3152 return ret;