flow: don't call scope_guard hooks twice at the end of functions
[smatch.git] / smatch_db.c
blobca7a0782bfda27790e3c1bec0ab51ed5c84f1f85
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 !(fn->symbol->ident && strncmp(fn->symbol->ident->name, "__smatch", 8)))
674 set_state(my_id, "db_incomplete", NULL, &incomplete);
675 if (row_count == 0 || row_count > 3000) {
676 mark_call_params_untracked(call);
677 return;
680 run_sql(callback, info, "select %s from return_states where %s order by file, return_id, type;",
681 cols, get_static_filter(fn->symbol));
684 bool db_incomplete(void)
686 return !!get_state(my_id, "db_incomplete", NULL);
689 #define CALL_IMPLIES 0
690 #define RETURN_IMPLIES 1
692 struct implies_info {
693 int type;
694 struct db_implies_cb_list *cb_list;
695 struct expression *expr;
696 struct symbol *sym;
699 void sql_select_implies(const char *cols, struct implies_info *info,
700 int (*callback)(void*, int, char**, char**))
702 if (info->type == RETURN_IMPLIES && inlinable(info->expr->fn)) {
703 mem_sql(callback, info,
704 "select %s from return_implies where call_id = '%lu';",
705 cols, (unsigned long)info->expr);
706 return;
709 run_sql(callback, info, "select %s from %s_implies where %s;",
710 cols,
711 info->type == CALL_IMPLIES ? "call" : "return",
712 get_static_filter(info->sym));
715 struct select_caller_info_data {
716 struct stree *final_states;
717 struct timeval start_time;
718 int prev_func_id;
719 int ignore;
720 int results;
723 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName);
725 static void sql_select_caller_info(struct select_caller_info_data *data,
726 const char *cols, struct symbol *sym)
728 if (__inline_fn) {
729 mem_sql(caller_info_callback, data,
730 "select %s from caller_info where call_id = %lu;",
731 cols, (unsigned long)__inline_fn);
732 return;
735 if (is_common_function(sym->ident->name))
736 return;
737 run_sql(caller_info_callback, data,
738 "select %s from common_caller_info where %s order by call_id;",
739 cols, get_static_filter(sym));
740 if (data->results)
741 return;
743 run_sql(caller_info_callback, data,
744 "select %s from caller_info where %s order by call_id;",
745 cols, get_static_filter(sym));
748 void select_caller_info_hook(void (*callback)(const char *name, struct symbol *sym, char *key, char *value), int type)
750 struct def_callback *def_callback = __alloc_def_callback(0);
752 def_callback->hook_type = type;
753 def_callback->callback = callback;
754 add_ptr_list(&select_caller_info_callbacks, def_callback);
757 void select_caller_name_sym(void (*fn)(const char *name, struct symbol *sym, char *value), int type)
759 struct def_name_sym_callback *callback = __alloc_def_name_sym_callback(0);
761 callback->hook_type = type;
762 callback->callback = fn;
763 add_ptr_list(&select_caller_name_sym_callbacks, callback);
767 * These call backs are used when the --info option is turned on to print struct
768 * member information. For example foo->bar could have a state in
769 * smatch_extra.c and also check_user.c.
771 void add_member_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
773 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
775 member_callback->owner = owner;
776 member_callback->callback = callback;
777 add_ptr_list(&member_callbacks, member_callback);
780 void add_caller_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
782 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
784 member_callback->owner = owner;
785 member_callback->callback = callback;
786 add_ptr_list(&member_callbacks_new, member_callback);
789 void add_return_info_callback(int owner,
790 void (*callback)(int return_id, char *return_ranges,
791 struct expression *returned_expr,
792 int param,
793 const char *printed_name,
794 struct sm_state *sm))
796 struct return_info_callback *return_callback = __alloc_return_info_callback(0);
798 return_callback->owner = owner;
799 return_callback->callback = callback;
800 add_ptr_list(&return_callbacks, return_callback);
803 void add_split_return_callback(void (*fn)(int return_id, char *return_ranges, struct expression *returned_expr))
805 struct returned_state_callback *callback = __alloc_returned_state_callback(0);
807 callback->callback = fn;
808 add_ptr_list(&returned_state_callbacks, callback);
811 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))
813 struct returned_member_callback *member_callback = __alloc_returned_member_callback(0);
815 member_callback->owner = owner;
816 member_callback->callback = callback;
817 add_ptr_list(&returned_member_callbacks, member_callback);
820 void select_call_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
822 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
824 cb->type = type;
825 cb->callback = callback;
826 add_ptr_list(&call_implies_cb_list, cb);
829 void select_return_implies_hook_early(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
831 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
833 cb->type = type;
834 cb->callback = callback;
835 add_ptr_list(&return_implies_cb_list_early, cb);
838 void select_return_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
840 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
842 cb->type = type;
843 cb->callback = callback;
844 add_ptr_list(&return_implies_cb_list_late, cb);
847 struct return_info {
848 struct expression *static_returns_call;
849 struct symbol *return_type;
850 struct range_list *return_range_list;
853 static int db_return_callback(void *_ret_info, int argc, char **argv, char **azColName)
855 struct return_info *ret_info = _ret_info;
856 struct range_list *rl;
857 struct expression *call_expr = ret_info->static_returns_call;
859 if (argc != 1)
860 return 0;
861 call_results_to_rl(call_expr, ret_info->return_type, argv[0], &rl);
862 ret_info->return_range_list = rl_union(ret_info->return_range_list, rl);
863 return 0;
866 static struct expression *cached_expr, *cached_no_args;
867 static const char *cached_str;
868 static struct range_list *cached_rl, *cached_str_rl, *cached_no_args_rl;
870 static void clear_cached_return_vals(void)
872 cached_expr = NULL;
873 cached_rl = NULL;
874 cached_str = NULL;
875 cached_str_rl = NULL;
876 cached_no_args = NULL;
877 cached_no_args_rl = NULL;
880 struct range_list *db_return_vals(struct expression *expr)
882 struct return_info ret_info = {};
883 struct sm_state *sm;
885 if (!expr)
886 return NULL;
888 if (is_fake_call(expr))
889 return NULL;
891 if (expr == cached_expr)
892 return clone_rl(cached_rl);
894 cached_expr = expr;
895 cached_rl = NULL;
897 sm = get_extra_sm_state(expr);
898 if (sm) {
899 cached_rl = clone_rl(estate_rl(sm->state));
900 return clone_rl(estate_rl(sm->state));
902 ret_info.static_returns_call = expr;
903 ret_info.return_type = get_type(expr);
904 if (!ret_info.return_type)
905 return NULL;
907 if (expr->fn->type != EXPR_SYMBOL || !expr->fn->symbol)
908 return NULL;
910 ret_info.return_range_list = NULL;
911 if (inlinable(expr->fn)) {
912 mem_sql(db_return_callback, &ret_info,
913 "select distinct return from return_states where call_id = '%lu';",
914 (unsigned long)expr);
915 } else {
916 run_sql(db_return_callback, &ret_info,
917 "select distinct return from return_states where %s;",
918 get_static_filter(expr->fn->symbol));
920 cached_rl = clone_rl(ret_info.return_range_list);
921 return ret_info.return_range_list;
924 struct range_list *db_return_vals_from_str(const char *fn_name)
926 struct return_info ret_info;
928 if (!fn_name)
929 return NULL;
930 if (fn_name == cached_str)
931 return clone_rl(cached_str_rl);
932 cached_str = fn_name;
933 cached_str_rl = NULL;
935 ret_info.static_returns_call = NULL;
936 ret_info.return_type = &llong_ctype;
937 ret_info.return_range_list = NULL;
939 run_sql(db_return_callback, &ret_info,
940 "select distinct return from return_states where function = '%s';",
941 fn_name);
942 cached_str_rl = clone_rl(ret_info.return_range_list);
943 return ret_info.return_range_list;
947 * This is used when we have a function that takes a function pointer as a
948 * parameter. "frob(blah, blah, my_function);" We know that the return values
949 * from frob() come from my_funcion() so we want to find the possible returns
950 * of my_function(), but we don't know which arguments are passed to it.
953 struct range_list *db_return_vals_no_args(struct expression *expr)
955 struct return_info ret_info = {};
957 if (!expr || expr->type != EXPR_SYMBOL)
958 return NULL;
960 if (expr == cached_no_args)
961 return clone_rl(cached_no_args_rl);
962 cached_no_args = expr;
963 cached_no_args_rl = NULL;
965 ret_info.static_returns_call = expr;
966 ret_info.return_type = get_type(expr);
967 ret_info.return_type = get_real_base_type(ret_info.return_type);
968 if (!ret_info.return_type)
969 return NULL;
971 run_sql(db_return_callback, &ret_info,
972 "select distinct return from return_states where %s;",
973 get_static_filter(expr->symbol));
975 cached_no_args_rl = clone_rl(ret_info.return_range_list);
976 return ret_info.return_range_list;
979 static void match_call_marker(struct expression *expr)
981 struct symbol *type;
983 type = get_type(expr->fn);
984 if (type && type->type == SYM_PTR)
985 type = get_real_base_type(type);
988 * we just want to record something in the database so that if we have
989 * two calls like: frob(4); frob(some_unkown); then on the receiving
990 * side we know that sometimes frob is called with unknown parameters.
993 sql_insert_caller_info(expr, INTERNAL, -1, "%call_marker%", type_to_str(type));
996 int is_recursive_member(const char *name)
998 char buf[256];
999 const char *p, *next;
1000 int size;
1002 p = strchr(name, '>');
1003 if (!p)
1004 return 0;
1005 p++;
1006 while (true) {
1007 next = strchr(p, '>');
1008 if (!next)
1009 return 0;
1010 next++;
1012 size = next - p;
1013 if (size >= sizeof(buf))
1014 return 0;
1015 memcpy(buf, p, size);
1016 buf[size] = '\0';
1017 if (strstr(next, buf))
1018 return 1;
1019 p = next;
1023 char *sm_to_arg_name(struct expression *expr, struct sm_state *sm)
1025 struct symbol *sym;
1026 const char *sm_name;
1027 char *name;
1028 bool is_address = false;
1029 bool add_star = false;
1030 char buf[256];
1031 char *ret = NULL;
1032 int len;
1034 expr = strip_expr(expr);
1035 if (!expr)
1036 return NULL;
1038 if (expr->type == EXPR_PREOP && expr->op == '&') {
1039 expr = strip_expr(expr->unop);
1040 is_address = true;
1043 name = expr_to_var_sym(expr, &sym);
1044 if (!name || !sym)
1045 goto free;
1046 if (sym != sm->sym)
1047 goto free;
1049 sm_name = sm->name;
1050 add_star = false;
1051 if (sm_name[0] == '*') {
1052 add_star = true;
1053 sm_name++;
1056 len = strlen(name);
1057 if (strncmp(name, sm_name, len) != 0)
1058 goto free;
1059 if (sm_name[len] == '\0') {
1060 snprintf(buf, sizeof(buf), "%s%s$",
1061 add_star ? "*" : "", is_address ? "*" : "");
1062 } else {
1063 if (sm_name[len] != '.' && sm_name[len] != '-')
1064 goto free;
1065 if (sm_name[len] == '-')
1066 len++;
1067 // FIXME does is_address really imply that sm_name[len] == '-'
1068 snprintf(buf, sizeof(buf), "%s$->%s", add_star ? "*" : "",
1069 sm_name + len);
1072 ret = alloc_sname(buf);
1073 free:
1074 free_string(name);
1075 return ret;
1078 static void print_struct_members(struct expression *call, struct expression *expr, int param,
1079 int owner,
1080 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm),
1081 bool new)
1083 struct sm_state *sm;
1084 const char *sm_name;
1085 char *name;
1086 struct symbol *sym;
1087 int len;
1088 char printed_name[256];
1089 int is_address = 0;
1090 bool add_star;
1091 struct symbol *type;
1093 expr = strip_expr(expr);
1094 if (!expr)
1095 return;
1096 type = get_type(expr);
1097 if (!new && type && type_bits(type) < type_bits(&ulong_ctype))
1098 return;
1100 if (expr->type == EXPR_PREOP && expr->op == '&') {
1101 expr = strip_expr(expr->unop);
1102 is_address = 1;
1105 name = expr_to_var_sym(expr, &sym);
1106 if (!name || !sym)
1107 goto free;
1109 len = strlen(name);
1110 FOR_EACH_SM(__get_cur_stree(), sm) {
1111 if (sm->owner != owner || sm->sym != sym)
1112 continue;
1114 sm_name = sm->name;
1115 add_star = false;
1116 if (sm_name[0] == '*') {
1117 add_star = true;
1118 sm_name++;
1120 // FIXME: simplify?
1121 if (!add_star && strcmp(name, sm_name) == 0) {
1122 if (is_address) {
1123 snprintf(printed_name, sizeof(printed_name), "*$");
1124 } else {
1125 if (new)
1126 snprintf(printed_name, sizeof(printed_name), "$");
1127 else
1128 continue;
1130 } else if (add_star && strcmp(name, sm_name) == 0) {
1131 snprintf(printed_name, sizeof(printed_name), "%s*$",
1132 is_address ? "*" : "");
1133 } else if (strncmp(name, sm_name, len) == 0) {
1134 if (sm_name[len] != '.' && sm_name[len] != '-')
1135 continue;
1136 if (is_address && sm_name[len] == '.') {
1137 snprintf(printed_name, sizeof(printed_name),
1138 "%s$->%s", add_star ? "*" : "",
1139 sm_name + len + 1);
1140 } else if (is_address && sm_name[len] == '-') {
1141 snprintf(printed_name, sizeof(printed_name),
1142 "%s(*$)%s", add_star ? "*" : "",
1143 sm_name + len);
1144 } else {
1145 snprintf(printed_name, sizeof(printed_name),
1146 "%s$%s", add_star ? "*" : "",
1147 sm_name + len);
1149 } else if (sm_name[0] == '&' && strncmp(name, sm_name + 1, len) == 0) {
1150 if (sm_name[len + 1] != '.' && sm_name[len + 1] != '-')
1151 continue;
1152 if (is_address && sm_name[len + 1] == '.') {
1153 snprintf(printed_name, sizeof(printed_name),
1154 "&%s$->%s", add_star ? "*" : "",
1155 sm_name + len + 2);
1156 } else if (is_address && sm_name[len] == '-') {
1157 snprintf(printed_name, sizeof(printed_name),
1158 "&%s(*$)%s", add_star ? "*" : "",
1159 sm_name + len + 1);
1160 } else {
1161 snprintf(printed_name, sizeof(printed_name),
1162 "&%s$%s", add_star ? "*" : "",
1163 sm_name + len + 1);
1165 } else {
1166 continue;
1168 if (is_recursive_member(printed_name))
1169 continue;
1170 callback(call, param, printed_name, sm);
1171 } END_FOR_EACH_SM(sm);
1172 free:
1173 free_string(name);
1176 static void match_call_info(struct expression *call)
1178 struct member_info_callback *cb;
1179 struct expression *arg;
1180 int i;
1182 FOR_EACH_PTR(member_callbacks, cb) {
1183 i = -1;
1184 FOR_EACH_PTR(call->args, arg) {
1185 i++;
1186 print_struct_members(call, arg, i, cb->owner, cb->callback, 0);
1187 } END_FOR_EACH_PTR(arg);
1188 } END_FOR_EACH_PTR(cb);
1191 static struct expression *get_fake_variable(struct expression *expr)
1193 struct expression *tmp;
1195 tmp = expr_get_fake_parent_expr(expr);
1196 if (!tmp || tmp->type != EXPR_ASSIGNMENT)
1197 return NULL;
1199 return tmp->left;
1202 static struct sm_state *get_returned_sm(struct expression *expr)
1204 struct expression *fake;
1206 fake = get_fake_variable(expr);
1207 if (fake)
1208 expr = fake;
1210 return get_sm_state_expr(SMATCH_EXTRA, expr);
1213 static void match_call_info_new(struct expression *call)
1215 struct member_info_callback *cb;
1216 struct expression *arg, *tmp;
1217 int i;
1219 if (!option_info && !__inline_call && !local_debug)
1220 return;
1222 FOR_EACH_PTR(member_callbacks_new, cb) {
1223 i = -1;
1224 FOR_EACH_PTR(call->args, arg) {
1225 i++;
1226 tmp = get_fake_variable(arg);
1227 if (!tmp)
1228 tmp = arg;
1229 __ignore_param_used++;
1230 print_struct_members(call, tmp, i, cb->owner, cb->callback, 1);
1231 __ignore_param_used--;
1232 } END_FOR_EACH_PTR(arg);
1233 } END_FOR_EACH_PTR(cb);
1236 static int get_param(int param, char **name, struct symbol **sym)
1238 struct symbol *arg;
1239 int i;
1241 i = 0;
1242 FOR_EACH_PTR(cur_func_sym->ctype.base_type->arguments, arg) {
1243 if (i == param) {
1244 *name = arg->ident->name;
1245 *sym = arg;
1246 return TRUE;
1248 i++;
1249 } END_FOR_EACH_PTR(arg);
1251 return FALSE;
1254 static int function_signature_matches(const char *sig)
1256 char *my_sig;
1258 my_sig = function_signature();
1259 if (!sig || !my_sig)
1260 return 1; /* default to matching */
1261 if (strcmp(my_sig, sig) == 0)
1262 return 1;
1263 return 0;
1266 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName)
1268 struct select_caller_info_data *data = _data;
1269 int func_id;
1270 long type;
1271 long param;
1272 char *key;
1273 char *value;
1274 char *name = NULL;
1275 struct symbol *sym = NULL;
1276 struct def_callback *def_callback;
1277 struct def_name_sym_callback *ns_callback;
1278 struct stree *stree;
1279 struct timeval cur_time;
1280 char fullname[256];
1281 char *p;
1283 data->results = 1;
1285 if (argc != 5)
1286 return 0;
1288 gettimeofday(&cur_time, NULL);
1289 if (cur_time.tv_sec - data->start_time.tv_sec > 10)
1290 return 0;
1292 func_id = atoi(argv[0]);
1293 errno = 0;
1294 type = strtol(argv[1], NULL, 10);
1295 param = strtol(argv[2], NULL, 10);
1296 if (errno)
1297 return 0;
1298 key = argv[3];
1299 value = argv[4];
1301 if (data->prev_func_id == -1)
1302 data->prev_func_id = func_id;
1303 if (func_id != data->prev_func_id) {
1304 stree = __pop_fake_cur_stree();
1305 if (!data->ignore)
1306 merge_stree(&data->final_states, stree);
1307 free_stree(&stree);
1308 __push_fake_cur_stree();
1309 __unnullify_path();
1310 data->prev_func_id = func_id;
1311 data->ignore = 0;
1314 if (data->ignore)
1315 return 0;
1316 if (type == INTERNAL &&
1317 !function_signature_matches(value)) {
1318 data->ignore = 1;
1319 return 0;
1322 if (param >= 0 && !get_param(param, &name, &sym))
1323 return 0;
1325 FOR_EACH_PTR(select_caller_info_callbacks, def_callback) {
1326 if (def_callback->hook_type == type)
1327 def_callback->callback(name, sym, key, value);
1328 } END_FOR_EACH_PTR(def_callback);
1330 p = strchr(key, '$');
1331 if (name && p)
1332 snprintf(fullname, sizeof(fullname), "%.*s%s%s", (int)(p - key), key, name, p + 1);
1333 else
1334 snprintf(fullname, sizeof(fullname), "%s", key);
1336 FOR_EACH_PTR(select_caller_name_sym_callbacks, ns_callback) {
1337 if (ns_callback->hook_type == type)
1338 ns_callback->callback(fullname, sym, value);
1339 } END_FOR_EACH_PTR(ns_callback);
1341 return 0;
1344 static struct string_list *ptr_names_done;
1345 static struct string_list *ptr_names;
1347 static int get_ptr_name(void *unused, int argc, char **argv, char **azColName)
1349 insert_string(&ptr_names, alloc_string(argv[0]));
1350 return 0;
1353 static char *get_next_ptr_name(void)
1355 char *ptr;
1357 FOR_EACH_PTR(ptr_names, ptr) {
1358 if (!insert_string(&ptr_names_done, ptr))
1359 continue;
1360 return ptr;
1361 } END_FOR_EACH_PTR(ptr);
1362 return NULL;
1365 static void get_ptr_names(unsigned long long file, const char *name)
1367 char sql_filter[1024];
1368 int before, after;
1370 if (file) {
1371 snprintf(sql_filter, 1024, "file = 0x%llx and function = '%s';",
1372 file, name);
1373 } else {
1374 snprintf(sql_filter, 1024, "function = '%s';", name);
1377 before = ptr_list_size((struct ptr_list *)ptr_names);
1379 run_sql(get_ptr_name, NULL,
1380 "select distinct ptr from function_ptr where %s",
1381 sql_filter);
1383 after = ptr_list_size((struct ptr_list *)ptr_names);
1384 if (before == after)
1385 return;
1387 while ((name = get_next_ptr_name()))
1388 get_ptr_names(0, name);
1391 static void match_data_from_db(struct symbol *sym)
1393 struct select_caller_info_data data = { .prev_func_id = -1 };
1394 struct sm_state *sm;
1395 struct stree *stree;
1396 struct timeval end_time;
1398 if (!sym || !sym->ident)
1399 return;
1401 set_fn_mtag(sym);
1402 gettimeofday(&data.start_time, NULL);
1404 __push_fake_cur_stree();
1405 __unnullify_path();
1407 if (!__inline_fn) {
1408 char *ptr;
1410 if (sym->ctype.modifiers & MOD_STATIC)
1411 get_ptr_names(get_base_file_id(), sym->ident->name);
1412 else
1413 get_ptr_names(0, sym->ident->name);
1415 if (ptr_list_size((struct ptr_list *)ptr_names) > 20) {
1416 __free_ptr_list((struct ptr_list **)&ptr_names);
1417 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1418 __free_fake_cur_stree();
1419 return;
1422 sql_select_caller_info(&data,
1423 "call_id, type, parameter, key, value",
1424 sym);
1427 stree = __pop_fake_cur_stree();
1428 if (!data.ignore)
1429 merge_stree(&data.final_states, stree);
1430 free_stree(&stree);
1431 __push_fake_cur_stree();
1432 __unnullify_path();
1433 data.prev_func_id = -1;
1434 data.ignore = 0;
1435 data.results = 0;
1437 FOR_EACH_PTR(ptr_names, ptr) {
1438 run_sql(caller_info_callback, &data,
1439 "select call_id, type, parameter, key, value"
1440 " from common_caller_info where function = '%s' order by call_id",
1441 ptr);
1442 } END_FOR_EACH_PTR(ptr);
1444 if (data.results) {
1445 FOR_EACH_PTR(ptr_names, ptr) {
1446 free_string(ptr);
1447 } END_FOR_EACH_PTR(ptr);
1448 goto free_ptr_names;
1451 FOR_EACH_PTR(ptr_names, ptr) {
1452 run_sql(caller_info_callback, &data,
1453 "select call_id, type, parameter, key, value"
1454 " from caller_info where function = '%s' order by call_id",
1455 ptr);
1456 free_string(ptr);
1457 } END_FOR_EACH_PTR(ptr);
1459 free_ptr_names:
1460 __free_ptr_list((struct ptr_list **)&ptr_names);
1461 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1462 } else {
1463 sql_select_caller_info(&data,
1464 "call_id, type, parameter, key, value",
1465 sym);
1468 stree = __pop_fake_cur_stree();
1469 if (!data.ignore)
1470 merge_stree(&data.final_states, stree);
1471 free_stree(&stree);
1473 gettimeofday(&end_time, NULL);
1474 if (end_time.tv_sec - data.start_time.tv_sec <= 10) {
1475 FOR_EACH_SM(data.final_states, sm) {
1476 __set_sm(sm);
1477 } END_FOR_EACH_SM(sm);
1480 free_stree(&data.final_states);
1483 static int return_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1485 struct implies_info *info = _info;
1486 struct db_implies_callback *cb;
1487 struct expression *arg = NULL;
1488 int type;
1489 int param;
1491 if (argc != 5)
1492 return 0;
1494 type = atoi(argv[1]);
1495 param = atoi(argv[2]);
1497 /* The caller doesn't pass the assignment so -1 can't be useful */
1498 if (param == -1)
1499 return 0;
1500 if (param >= 0) {
1501 arg = get_argument_from_call_expr(info->expr->args, param);
1502 if (!arg)
1503 return 0;
1506 FOR_EACH_PTR(info->cb_list, cb) {
1507 if (cb->type != type)
1508 continue;
1509 cb->callback(info->expr, arg, argv[3], argv[4]);
1510 } END_FOR_EACH_PTR(cb);
1512 return 0;
1515 static int call_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1517 struct implies_info *info = _info;
1518 struct db_implies_callback *cb;
1519 struct expression *arg;
1520 struct symbol *sym;
1521 char *name;
1522 int type;
1523 int param;
1525 if (argc != 5)
1526 return 0;
1528 type = atoi(argv[1]);
1529 param = atoi(argv[2]);
1531 if (!get_param(param, &name, &sym))
1532 return 0;
1533 arg = symbol_expression(sym);
1534 if (!arg)
1535 return 0;
1537 FOR_EACH_PTR(info->cb_list, cb) {
1538 if (cb->type != type)
1539 continue;
1540 cb->callback(info->expr, arg, argv[3], argv[4]);
1541 } END_FOR_EACH_PTR(cb);
1543 return 0;
1546 static void match_return_implies_helper(struct expression *expr, struct db_implies_cb_list *cb_list)
1548 struct implies_info info = {
1549 .type = RETURN_IMPLIES,
1550 .cb_list = cb_list,
1553 if (expr->fn->type != EXPR_SYMBOL ||
1554 !expr->fn->symbol)
1555 return;
1556 info.expr = expr;
1557 info.sym = expr->fn->symbol;
1558 sql_select_implies("function, type, parameter, key, value", &info,
1559 return_implies_callbacks);
1562 static void match_return_implies_early(struct expression *expr)
1564 match_return_implies_helper(expr, return_implies_cb_list_early);
1567 static void match_return_implies_late(struct expression *expr)
1569 match_return_implies_helper(expr, return_implies_cb_list_late);
1572 static void match_call_implies(struct symbol *sym)
1574 struct implies_info info = {
1575 .type = CALL_IMPLIES,
1576 .cb_list = call_implies_cb_list,
1579 if (!sym || !sym->ident)
1580 return;
1582 info.sym = sym;
1583 sql_select_implies("function, type, parameter, key, value", &info,
1584 call_implies_callbacks);
1587 static char *get_fn_param_str(struct expression *expr)
1589 struct expression *tmp;
1590 int param;
1591 char buf[32];
1593 tmp = get_assigned_expr(expr);
1594 if (tmp)
1595 expr = tmp;
1596 expr = strip_expr(expr);
1597 if (!expr || expr->type != EXPR_CALL)
1598 return NULL;
1599 expr = strip_expr(expr->fn);
1600 if (!expr || expr->type != EXPR_SYMBOL)
1601 return NULL;
1602 param = get_param_num(expr);
1603 if (param < 0)
1604 return NULL;
1606 snprintf(buf, sizeof(buf), "[r $%d]", param);
1607 return alloc_sname(buf);
1610 static char *get_return_compare_is_param(struct expression *expr)
1612 char *var;
1613 char buf[256];
1614 int comparison;
1615 int param;
1617 param = get_param_num(expr);
1618 if (param < 0)
1619 return NULL;
1621 var = expr_to_var(expr);
1622 if (!var)
1623 return NULL;
1624 snprintf(buf, sizeof(buf), "%s orig", var);
1625 comparison = get_comparison_strings(var, buf);
1626 free_string(var);
1628 if (!comparison)
1629 return NULL;
1631 snprintf(buf, sizeof(buf), "[%s$%d]", show_special(comparison), param);
1632 return alloc_sname(buf);
1635 static char *get_return_compare_str(struct expression *expr)
1637 char *compare_str;
1639 compare_str = get_return_compare_is_param(expr);
1640 if (compare_str)
1641 return compare_str;
1643 compare_str = expr_lte_to_param(expr, -1);
1644 if (compare_str)
1645 return compare_str;
1647 return expr_param_comparison(expr, -1);
1650 static const char *get_return_ranges_str(struct expression *expr, struct range_list **rl_p)
1652 struct expression *fake;
1653 struct range_list *rl;
1654 const char *return_ranges;
1655 sval_t sval;
1656 const char *container_of_str;
1657 const char *math_str;
1658 char *fn_param_str;
1659 char *compare_str;
1660 char buf[128];
1662 *rl_p = NULL;
1664 if (!expr)
1665 return alloc_sname("");
1667 fake = get_fake_variable(expr);
1668 if (fake)
1669 expr = fake;
1671 container_of_str = get_container_of_str(expr);
1673 if (get_implied_value(expr, &sval)) {
1674 sval = sval_cast(cur_func_return_type(), sval);
1675 *rl_p = alloc_rl(sval, sval);
1676 return_ranges = sval_to_str_or_err_ptr(sval);
1677 if (container_of_str) {
1678 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1679 return alloc_sname(buf);
1681 return return_ranges;
1684 fn_param_str = get_fn_param_str(expr);
1685 math_str = get_param_key_swap_dollar(expr);
1686 compare_str = expr_equal_to_param(expr, -1);
1687 if (!math_str)
1688 math_str = get_value_in_terms_of_parameter_math(expr);
1690 if (get_implied_rl(expr, &rl) && !is_whole_rl(rl)) {
1691 rl = cast_rl(cur_func_return_type(), rl);
1692 return_ranges = show_rl(rl);
1693 } else if (get_imaginary_absolute(expr, &rl)){
1694 rl = cast_rl(cur_func_return_type(), rl);
1695 return alloc_sname(show_rl(rl));
1696 } else {
1697 get_absolute_rl(expr, &rl);
1698 rl = cast_rl(cur_func_return_type(), rl);
1699 return_ranges = show_rl(rl);
1701 *rl_p = rl;
1703 if (container_of_str) {
1704 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1705 return alloc_sname(buf);
1707 if (fn_param_str) {
1708 snprintf(buf, sizeof(buf), "%s%s", return_ranges, fn_param_str);
1709 return alloc_sname(buf);
1711 if (compare_str) {
1712 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1713 return alloc_sname(buf);
1715 if (math_str) {
1716 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, math_str);
1717 return alloc_sname(buf);
1719 compare_str = get_return_compare_str(expr);
1720 if (compare_str) {
1721 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1722 return alloc_sname(buf);
1725 return return_ranges;
1728 static void match_return_info(int return_id, char *return_ranges, struct expression *expr)
1730 sql_insert_return_states(return_id, return_ranges, INTERNAL, -1, "", function_signature());
1733 static bool call_return_state_hooks_conditional(struct expression *expr)
1735 int final_pass_orig = final_pass;
1736 static int recurse;
1738 if (recurse >= 2)
1739 return false;
1740 if (!expr ||
1741 (expr->type != EXPR_CONDITIONAL && expr->type != EXPR_SELECT))
1742 return false;
1744 recurse++;
1746 __push_fake_cur_stree();
1748 final_pass = 0;
1749 __split_whole_condition(expr->conditional);
1750 final_pass = final_pass_orig;
1752 call_return_state_hooks(expr->cond_true ?: expr->conditional);
1754 __push_true_states();
1755 __use_false_states();
1757 call_return_state_hooks(expr->cond_false);
1759 __merge_true_states();
1760 __free_fake_cur_stree();
1762 recurse--;
1763 return true;
1766 static bool handle_forced_split(const char *return_ranges, struct expression *expr)
1768 struct split_data *data = NULL;
1769 struct expression *compare;
1770 struct range_list *rl;
1771 char buf[64];
1772 char *math;
1773 sval_t sval;
1774 bool undo;
1775 int i;
1777 for (i = 0; i < split_count; i++) {
1778 if (get_function() &&
1779 strcmp(get_function(), forced_splits[i]->func) == 0) {
1780 data = forced_splits[i];
1781 break;
1784 if (!data)
1785 return false;
1787 // FIXME: this works for copy_to/from_user() because the only thing we
1788 // care about is zero/non-zero
1789 if (strcmp(data->rl, "0") != 0)
1790 return false;
1792 compare = compare_expression(expr, SPECIAL_EQUAL, zero_expr());
1793 if (!compare)
1794 return false;
1795 if (get_implied_value(compare, &sval))
1796 return false;
1798 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
1799 call_return_states_callbacks("0", expr);
1800 if (undo)
1801 end_assume();
1803 undo = assume(compare_expression(expr, SPECIAL_NOTEQUAL, zero_expr()));
1804 if (get_implied_rl(expr, &rl)) {
1805 math = strchr(return_ranges, '[');
1806 snprintf(buf, sizeof(buf), "%s%s", show_rl(rl), math ?: "");
1807 } else {
1808 snprintf(buf, sizeof(buf), "%s", return_ranges);
1810 call_return_states_callbacks(buf, expr);
1811 if (undo)
1812 end_assume();
1814 return true;
1817 static void call_return_states_callbacks(const char *return_ranges, struct expression *expr)
1819 struct returned_state_callback *cb;
1821 return_ranges = replace_return_ranges(return_ranges);
1822 if (is_delete_return(return_ranges))
1823 return;
1824 if (is_project_delete_return(expr))
1825 return;
1826 if (handle_forced_split(return_ranges, expr))
1827 return;
1829 return_id++;
1830 FOR_EACH_PTR(returned_state_callbacks, cb) {
1831 cb->callback(return_id, (char *)return_ranges, expr);
1832 } END_FOR_EACH_PTR(cb);
1835 static void call_return_state_hooks_compare(struct expression *expr)
1837 char *return_ranges;
1838 int final_pass_orig = final_pass;
1839 sval_t sval = { .type = &int_ctype };
1840 sval_t ret;
1842 if (!get_implied_value(expr, &ret))
1843 ret.value = -1;
1845 __push_fake_cur_stree();
1847 final_pass = 0;
1848 __split_whole_condition(expr);
1849 final_pass = final_pass_orig;
1851 if (ret.value != 0) {
1852 return_ranges = alloc_sname("1");
1853 sval.value = 1;
1854 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1856 call_return_states_callbacks(return_ranges, expr);
1859 __push_true_states();
1860 __use_false_states();
1862 if (ret.value != 1) {
1863 return_ranges = alloc_sname("0");
1864 sval.value = 0;
1865 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1867 call_return_states_callbacks(return_ranges, expr);
1870 __merge_true_states();
1871 __free_fake_cur_stree();
1874 static bool is_implies_function(struct expression *expr)
1876 struct range_list *rl;
1878 if (!expr)
1879 return false;
1881 rl = get_range_implications(get_function());
1882 if (!rl)
1883 return false;
1885 sm_msg("%s: is implied", __func__);
1886 return true;
1889 static int ptr_in_list(struct sm_state *sm, struct state_list *slist)
1891 struct sm_state *tmp;
1893 FOR_EACH_PTR(slist, tmp) {
1894 if (strcmp(tmp->state->name, sm->state->name) == 0)
1895 return 1;
1896 } END_FOR_EACH_PTR(tmp);
1898 return 0;
1901 static int split_possible_helper(struct sm_state *sm, struct expression *expr)
1903 struct range_list *rl;
1904 char *return_ranges;
1905 struct sm_state *tmp;
1906 int ret = 0;
1907 int nr_possible, nr_states;
1908 char *compare_str;
1909 char buf[128];
1910 struct state_list *already_handled = NULL;
1911 sval_t sval;
1913 if (!sm || !sm->merged)
1914 return 0;
1916 if (too_many_possible(sm) && !is_implies_function(expr))
1917 return 0;
1919 /* bail if it gets too complicated */
1920 nr_possible = 0;
1921 FOR_EACH_PTR(sm->possible, tmp) {
1922 if (tmp->merged)
1923 continue;
1924 if (ptr_in_list(tmp, already_handled))
1925 continue;
1926 add_ptr_list(&already_handled, tmp);
1927 nr_possible++;
1928 } END_FOR_EACH_PTR(tmp);
1929 free_slist(&already_handled);
1930 nr_states = get_db_state_count();
1931 if (nr_states * nr_possible >= 2000 && !is_implies_function(expr))
1932 return 0;
1934 FOR_EACH_PTR(sm->possible, tmp) {
1935 if (!is_leaf(tmp))
1936 continue;
1937 if (ptr_in_list(tmp, already_handled))
1938 continue;
1939 add_ptr_list(&already_handled, tmp);
1941 ret = 1;
1942 __push_fake_cur_stree();
1944 overwrite_states_using_pool(sm, tmp);
1946 rl = cast_rl(cur_func_return_type(), estate_rl(tmp->state));
1947 return_ranges = show_rl(rl);
1948 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(clone_rl(rl)));
1949 compare_str = get_return_compare_str(expr);
1950 /* ignore obvious stuff like 0 <= param */
1951 /* Is this worthile when we have PARAM_COMPARE? */
1952 if (compare_str &&
1953 strncmp(compare_str, "[=", 2) != 0 &&
1954 rl_to_sval(rl, &sval))
1955 compare_str = NULL;
1956 if (compare_str) {
1957 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1958 return_ranges = alloc_sname(buf);
1961 call_return_states_callbacks(return_ranges, expr);
1963 __free_fake_cur_stree();
1964 } END_FOR_EACH_PTR(tmp);
1966 free_slist(&already_handled);
1968 return ret;
1971 static int call_return_state_hooks_split_possible(struct expression *expr)
1973 struct sm_state *sm;
1975 if (!expr)
1976 return 0;
1978 sm = get_returned_sm(expr);
1979 return split_possible_helper(sm, expr);
1982 static bool has_empty_state(struct sm_state *sm)
1984 struct sm_state *tmp;
1986 FOR_EACH_PTR(sm->possible, tmp) {
1987 if (!estate_rl(tmp->state))
1988 return true;
1989 } END_FOR_EACH_PTR(tmp);
1991 return false;
1994 static bool has_possible_negative(struct sm_state *sm)
1996 struct sm_state *tmp;
1998 if (!type_signed(estate_type(sm->state)))
1999 return false;
2001 FOR_EACH_PTR(sm->possible, tmp) {
2002 if (!estate_rl(tmp->state))
2003 continue;
2004 if (sval_is_negative(estate_min(tmp->state)) &&
2005 sval_is_negative(estate_max(tmp->state)))
2006 return true;
2007 } END_FOR_EACH_PTR(tmp);
2009 return false;
2012 static bool has_separate_zero_null(struct sm_state *sm)
2014 struct sm_state *tmp;
2015 sval_t sval;
2017 FOR_EACH_PTR(sm->possible, tmp) {
2018 if (!estate_get_single_value(tmp->state, &sval))
2019 continue;
2020 if (sval.value == 0)
2021 return true;
2022 } END_FOR_EACH_PTR(tmp);
2024 return false;
2027 static int split_positive_from_negative(struct expression *expr)
2029 struct sm_state *sm;
2030 struct range_list *rl;
2031 const char *return_ranges;
2032 struct range_list *ret_rl;
2033 bool separate_zero;
2034 int undo;
2036 /* We're going to print the states 3 times */
2037 if (get_db_state_count() > 10000 / 3)
2038 return 0;
2040 if (!get_implied_rl(expr, &rl) || !rl)
2041 return 0;
2042 /* Forget about INT_MAX and larger */
2043 if (rl_max(rl).value <= 0)
2044 return 0;
2045 if (!sval_is_negative(rl_min(rl)))
2046 return 0;
2048 sm = get_returned_sm(expr);
2049 if (!sm)
2050 return 0;
2051 if (has_empty_state(sm))
2052 return 0;
2053 if (!has_possible_negative(sm))
2054 return 0;
2055 separate_zero = has_separate_zero_null(sm);
2057 if (!assume(compare_expression(expr, separate_zero ? '>' : SPECIAL_GTE, zero_expr())))
2058 return 0;
2060 return_ranges = get_return_ranges_str(expr, &ret_rl);
2061 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2062 call_return_states_callbacks(return_ranges, expr);
2064 end_assume();
2066 if (separate_zero) {
2067 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
2069 return_ranges = get_return_ranges_str(expr, &ret_rl);
2070 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2071 call_return_states_callbacks(return_ranges, expr);
2073 if (undo)
2074 end_assume();
2077 undo = assume(compare_expression(expr, '<', zero_expr()));
2079 return_ranges = get_return_ranges_str(expr, &ret_rl);
2080 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2081 call_return_states_callbacks(return_ranges, expr);
2083 if (undo)
2084 end_assume();
2086 return 1;
2089 static int call_return_state_hooks_split_null_non_null_zero(struct expression *expr)
2091 struct range_list *rl;
2092 struct range_list *nonnull_rl;
2093 sval_t null_sval;
2094 struct range_list *null_rl = NULL;
2095 char *return_ranges;
2096 struct sm_state *sm;
2097 struct smatch_state *state;
2098 int nr_states;
2099 int final_pass_orig = final_pass;
2101 if (!expr || expr_equal_to_param(expr, -1))
2102 return 0;
2103 if (expr->type == EXPR_CALL)
2104 return 0;
2106 sm = get_returned_sm(expr);
2107 if (!sm)
2108 return 0;
2109 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2110 return 0;
2111 state = sm->state;
2112 if (!estate_rl(state))
2113 return 0;
2114 if (estate_min(state).value == 0 && estate_max(state).value == 0)
2115 return 0;
2116 if (has_possible_negative(sm))
2117 return 0;
2118 if (!has_separate_zero_null(sm))
2119 return 0;
2121 nr_states = get_db_state_count();
2122 if (option_info && nr_states >= 1500)
2123 return 0;
2125 rl = estate_rl(state);
2127 __push_fake_cur_stree();
2129 final_pass = 0;
2130 __split_whole_condition(expr);
2131 final_pass = final_pass_orig;
2133 nonnull_rl = rl_filter(rl, rl_zero());
2134 return_ranges = show_rl(nonnull_rl);
2135 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonnull_rl));
2137 call_return_states_callbacks(return_ranges, expr);
2139 __push_true_states();
2140 __use_false_states();
2142 return_ranges = alloc_sname("0");
2143 null_sval = sval_type_val(rl_type(rl), 0);
2144 add_range(&null_rl, null_sval, null_sval);
2145 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(null_rl));
2146 call_return_states_callbacks(return_ranges, expr);
2148 __merge_true_states();
2149 __free_fake_cur_stree();
2151 return 1;
2154 static bool is_neg_and_pos_err_code(struct range_list *rl)
2156 struct data_range *tmp, *last;
2158 if (option_project != PROJ_KERNEL)
2159 return false;
2160 if (!rl)
2161 return false;
2163 /* Assume s32min-(14),(-12)-(-1),1-s32max is an error code. */
2164 last = last_ptr_list((struct ptr_list *)rl);
2165 if (last->max.value >= 0 &&
2166 (last->min.value != 1 ||
2167 last->max.value != INT_MAX))
2168 return false;
2171 FOR_EACH_PTR(rl, tmp) {
2172 if (tmp == last)
2173 break;
2174 if (tmp->min.value != INT_MIN && tmp->min.value < -4095)
2175 return false;
2176 if (tmp->max.value < -4095 || tmp->max.value >= 0)
2177 return false;
2178 } END_FOR_EACH_PTR(tmp);
2180 return true;
2183 static bool is_kernel_success_fail(struct sm_state *sm)
2185 struct sm_state *tmp;
2186 struct range_list *rl;
2187 bool has_zero = false;
2188 bool has_neg = false;
2190 if (!sm)
2191 return false;
2193 if (!type_signed(estate_type(sm->state)))
2194 return false;
2196 FOR_EACH_PTR(sm->possible, tmp) {
2197 rl = estate_rl(tmp->state);
2198 if (!rl)
2199 return false;
2200 if (!is_leaf(tmp))
2201 continue;
2202 if (rl_min(rl).value == 0 && rl_max(rl).value == 0) {
2203 has_zero = true;
2204 continue;
2206 has_neg = true;
2207 if (is_neg_and_pos_err_code(estate_rl(tmp->state)))
2208 continue;
2209 return false;
2210 } END_FOR_EACH_PTR(tmp);
2212 return has_zero && has_neg;
2215 static int call_return_state_hooks_split_success_fail(struct expression *expr)
2217 struct expression *tmp_ret;
2218 struct sm_state *sm;
2219 struct range_list *rl;
2220 struct range_list *nonzero_rl;
2221 sval_t zero_sval;
2222 struct range_list *zero_rl = NULL;
2223 int nr_states;
2224 char *return_ranges;
2225 int final_pass_orig = final_pass;
2227 if (option_project != PROJ_KERNEL)
2228 return 0;
2230 nr_states = get_db_state_count();
2231 if (nr_states > 2000)
2232 return 0;
2234 tmp_ret = get_fake_variable(expr);
2235 if (!tmp_ret)
2236 tmp_ret = expr;
2237 sm = get_returned_sm(tmp_ret);
2238 if (!sm)
2239 return 0;
2240 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2241 return 0;
2242 if (!is_kernel_success_fail(sm))
2243 return 0;
2245 rl = estate_rl(sm->state);
2246 if (!rl)
2247 return 0;
2249 __push_fake_cur_stree();
2251 final_pass = 0;
2252 __split_whole_condition(tmp_ret);
2253 final_pass = final_pass_orig;
2255 nonzero_rl = rl_filter(rl, rl_zero());
2256 nonzero_rl = cast_rl(cur_func_return_type(), nonzero_rl);
2257 return_ranges = show_rl(nonzero_rl);
2258 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonzero_rl));
2260 call_return_states_callbacks(return_ranges, expr);
2262 __push_true_states();
2263 __use_false_states();
2265 return_ranges = alloc_sname("0");
2266 zero_sval = sval_type_val(rl_type(rl), 0);
2267 add_range(&zero_rl, zero_sval, zero_sval);
2268 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(zero_rl));
2269 call_return_states_callbacks(return_ranges, expr);
2271 __merge_true_states();
2272 __free_fake_cur_stree();
2274 return 1;
2277 static int is_boolean(struct expression *expr)
2279 struct range_list *rl;
2281 if (!get_implied_rl(expr, &rl))
2282 return 0;
2283 if (rl_min(rl).value == 0 && rl_max(rl).value == 1)
2284 return 1;
2285 return 0;
2288 static int splitable_function_call(struct expression *expr)
2290 struct sm_state *sm;
2292 if (!expr || expr->type != EXPR_CALL)
2293 return 0;
2294 sm = get_extra_sm_state(expr);
2295 return split_possible_helper(sm, expr);
2298 static struct sm_state *find_bool_param(void)
2300 struct stree *start_states;
2301 struct symbol *arg;
2302 struct sm_state *sm, *tmp;
2303 sval_t sval;
2305 start_states = get_start_states();
2307 FOR_EACH_PTR_REVERSE(cur_func_sym->ctype.base_type->arguments, arg) {
2308 if (!arg->ident)
2309 continue;
2310 sm = get_sm_state_stree(start_states, SMATCH_EXTRA, arg->ident->name, arg);
2311 if (!sm)
2312 continue;
2313 if (rl_min(estate_rl(sm->state)).value != 0 ||
2314 rl_max(estate_rl(sm->state)).value != 1)
2315 continue;
2316 goto found;
2317 } END_FOR_EACH_PTR_REVERSE(arg);
2319 return NULL;
2321 found:
2323 * Check if it's splitable. If not, then splitting it up is likely not
2324 * useful for the callers.
2326 FOR_EACH_PTR(sm->possible, tmp) {
2327 if (is_merged(tmp))
2328 continue;
2329 if (!estate_get_single_value(tmp->state, &sval))
2330 return NULL;
2331 } END_FOR_EACH_PTR(tmp);
2333 return sm;
2336 static int split_on_bool_sm(struct sm_state *sm, struct expression *expr)
2338 struct range_list *ret_rl;
2339 const char *return_ranges;
2340 struct sm_state *tmp;
2341 int ret = 0;
2342 struct state_list *already_handled = NULL;
2344 if (!sm || !sm->merged)
2345 return 0;
2347 if (too_many_possible(sm))
2348 return 0;
2350 FOR_EACH_PTR(sm->possible, tmp) {
2351 if (tmp->merged)
2352 continue;
2353 if (ptr_in_list(tmp, already_handled))
2354 continue;
2355 add_ptr_list(&already_handled, tmp);
2357 ret = 1;
2358 __push_fake_cur_stree();
2360 overwrite_states_using_pool(sm, tmp);
2362 return_ranges = get_return_ranges_str(expr, &ret_rl);
2363 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2364 call_return_states_callbacks(return_ranges, expr);
2366 __free_fake_cur_stree();
2367 } END_FOR_EACH_PTR(tmp);
2369 free_slist(&already_handled);
2371 return ret;
2374 static int split_by_bool_param(struct expression *expr)
2376 struct sm_state *start_sm, *sm;
2377 sval_t sval;
2379 start_sm = find_bool_param();
2380 if (!start_sm)
2381 return 0;
2382 sm = get_sm_state(SMATCH_EXTRA, start_sm->name, start_sm->sym);
2383 if (!sm || estate_get_single_value(sm->state, &sval))
2384 return 0;
2386 if (get_db_state_count() * 2 >= 2000)
2387 return 0;
2389 return split_on_bool_sm(sm, expr);
2392 static int split_by_null_nonnull_param(struct expression *expr)
2394 struct symbol *arg;
2395 struct sm_state *sm;
2396 int nr_possible;
2398 arg = first_ptr_list((struct ptr_list *)cur_func_sym->ctype.base_type->arguments);
2399 if (!arg || !arg->ident)
2400 return 0;
2401 if (get_real_base_type(arg)->type != SYM_PTR)
2402 return 0;
2404 if (param_was_set_var_sym(arg->ident->name, arg))
2405 return 0;
2406 sm = get_sm_state(SMATCH_EXTRA, arg->ident->name, arg);
2407 if (!sm)
2408 return 0;
2410 if (!has_separate_zero_null(sm))
2411 return 0;
2413 nr_possible = ptr_list_size((struct ptr_list *)sm->possible);
2414 if (get_db_state_count() * nr_possible >= 2000)
2415 return 0;
2417 return split_on_bool_sm(sm, expr);
2420 static void call_hooks_based_on_pool(struct expression *expr, struct sm_state *gate_sm, struct sm_state *pool_sm)
2422 struct range_list *ret_rl;
2423 const char *return_ranges;
2425 __push_fake_cur_stree();
2427 overwrite_states_using_pool(gate_sm, pool_sm);
2429 return_ranges = get_return_ranges_str(expr, &ret_rl);
2430 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2431 call_return_states_callbacks(return_ranges, expr);
2433 __free_fake_cur_stree();
2436 static bool split_by_impossible(struct expression *expr)
2438 static int impossible_id;
2439 struct sm_state *sm, *tmp;
2440 int nr_states;
2442 if (!impossible_id)
2443 impossible_id = id_from_name("register_impossible_return");
2444 if (!impossible_id)
2445 return false;
2448 * The only states for register_impossible_return are &impossible,
2449 * &undefined and &merged. This function will break otherwise.
2452 sm = get_sm_state(impossible_id, "impossible", NULL);
2453 if (!sm || sm->state != &merged)
2454 return false;
2456 nr_states = get_db_state_count();
2457 if (nr_states >= 1000)
2458 return false;
2460 /* handle possible */
2461 FOR_EACH_PTR(sm->possible, tmp) {
2462 if (!is_leaf(tmp))
2463 continue;
2464 if (tmp->state != &undefined)
2465 continue;
2466 call_hooks_based_on_pool(expr, sm, tmp);
2467 goto impossible;
2468 } END_FOR_EACH_PTR(tmp);
2470 impossible:
2471 /* handle impossible */
2472 FOR_EACH_PTR(sm->possible, tmp) {
2473 if (!is_leaf(tmp))
2474 continue;
2475 if (strcmp(tmp->state->name, "impossible") != 0)
2476 continue;
2477 call_hooks_based_on_pool(expr, sm, tmp);
2478 return true;
2479 } END_FOR_EACH_PTR(tmp);
2481 return false;
2484 struct expression *strip_expr_statement(struct expression *expr)
2486 struct expression *orig = expr;
2487 struct statement *stmt, *last_stmt;
2489 if (!expr)
2490 return NULL;
2491 if (expr->type == EXPR_PREOP && expr->op == '(')
2492 expr = expr->unop;
2493 if (expr->type != EXPR_STATEMENT)
2494 return orig;
2495 stmt = expr->statement;
2496 if (!stmt || stmt->type != STMT_COMPOUND)
2497 return orig;
2499 last_stmt = last_ptr_list((struct ptr_list *)stmt->stmts);
2500 if (!last_stmt || last_stmt->type == STMT_LABEL)
2501 last_stmt = last_stmt->label_statement;
2502 if (!last_stmt || last_stmt->type != STMT_EXPRESSION)
2503 return orig;
2504 return strip_expr(last_stmt->expression);
2507 static bool is_kernel_error_path(struct expression *expr)
2509 struct range_list *rl;
2511 if (option_project != PROJ_KERNEL)
2512 return false;
2514 if (!get_implied_rl(expr, &rl))
2515 return false;
2516 if (rl_type(rl) != &int_ctype)
2517 return false;
2518 if (!is_neg_and_pos_err_code(rl))
2519 return false;
2520 return true;
2523 static void call_return_state_hooks(struct expression *expr)
2525 struct range_list *ret_rl;
2526 const char *return_ranges;
2527 int nr_states;
2528 sval_t sval;
2530 if (debug_db) {
2531 struct range_list *rl = NULL;
2533 get_absolute_rl(expr, &rl);
2534 sm_msg("RETURN: expr='%s' rl='%s' %lu states%s", expr_to_str(expr),
2535 show_rl(rl), stree_count(__get_cur_stree()),
2536 is_impossible_path() ? " (impossible path)" : "");
2539 if (__path_is_null())
2540 return;
2542 if (is_impossible_path())
2543 goto vanilla;
2545 if (expr && (expr->type == EXPR_COMPARE ||
2546 !get_implied_value(expr, &sval)) &&
2547 (is_condition(expr) || is_boolean(expr))) {
2548 call_return_state_hooks_compare(expr);
2549 if (debug_db)
2550 sm_msg("%s: bool", __func__);
2551 return;
2552 } else if (call_return_state_hooks_conditional(expr)) {
2553 if (debug_db)
2554 sm_msg("%s: condition", __func__);
2555 return;
2556 } else if (is_kernel_error_path(expr)) {
2557 if (debug_db)
2558 sm_msg("%s: kernel error path", __func__);
2559 goto vanilla;
2560 } else if (call_return_state_hooks_split_success_fail(expr)) {
2561 if (debug_db)
2562 sm_msg("%s: success_fail", __func__);
2563 return;
2564 } else if (call_return_state_hooks_split_possible(expr)) {
2565 if (debug_db)
2566 sm_msg("%s: split_possible", __func__);
2567 return;
2568 } else if (split_positive_from_negative(expr)) {
2569 if (debug_db)
2570 sm_msg("%s: positive negative", __func__);
2571 return;
2572 } else if (call_return_state_hooks_split_null_non_null_zero(expr)) {
2573 if (debug_db)
2574 sm_msg("%s: split zero non-zero", __func__);
2575 return;
2576 } else if (splitable_function_call(expr)) {
2577 if (debug_db)
2578 sm_msg("%s: split_function_call", __func__);
2579 return;
2580 } else if (split_by_bool_param(expr)) {
2581 if (debug_db)
2582 sm_msg("%s: bool param", __func__);
2583 return;
2584 } else if (split_by_null_nonnull_param(expr)) {
2585 if (debug_db)
2586 sm_msg("%s: null non-null param", __func__);
2587 return;
2588 } else if (split_by_impossible(expr)) {
2589 if (debug_db)
2590 sm_msg("%s: split by impossible", __func__);
2591 return;
2594 vanilla:
2595 return_ranges = get_return_ranges_str(expr, &ret_rl);
2596 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2598 nr_states = get_db_state_count();
2599 if (nr_states >= 10000) {
2600 return_id++;
2601 match_return_info(return_id, (char *)return_ranges, expr);
2602 print_limited_param_set(return_id, (char *)return_ranges, expr);
2603 mark_all_params_untracked(return_id, (char *)return_ranges, expr);
2604 return;
2606 call_return_states_callbacks(return_ranges, expr);
2607 if (debug_db)
2608 sm_msg("%s: vanilla", __func__);
2611 static void print_returned_struct_members(int return_id, char *return_ranges, struct expression *expr)
2613 struct returned_member_callback *cb;
2614 struct sm_state *sm;
2615 struct symbol *type;
2616 char *name;
2617 char member_name[256];
2618 int len;
2620 type = get_type(expr);
2621 if (!type || type->type != SYM_PTR)
2622 return;
2623 name = expr_to_var(expr);
2624 if (!name)
2625 return;
2627 len = strlen(name);
2628 FOR_EACH_PTR(returned_member_callbacks, cb) {
2629 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2630 if (sm->name[0] == '*' && strcmp(sm->name + 1, name) == 0) {
2631 strcpy(member_name, "*$");
2632 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2633 continue;
2635 if (strncmp(sm->name, name, len) != 0)
2636 continue;
2637 if (strncmp(sm->name + len, "->", 2) != 0)
2638 continue;
2639 snprintf(member_name, sizeof(member_name), "$%s", sm->name + len);
2640 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2641 } END_FOR_EACH_SM(sm);
2642 } END_FOR_EACH_PTR(cb);
2644 free_string(name);
2647 static void print_return_struct_info(int return_id, char *return_ranges,
2648 struct expression *expr,
2649 struct symbol *sym,
2650 struct return_info_callback *cb)
2652 struct sm_state *sm;
2653 const char *printed_name;
2654 int param;
2656 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2657 param = get_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2658 if (!printed_name)
2659 continue;
2660 if (param < 0)
2661 continue;
2662 cb->callback(return_id, return_ranges, expr, param, printed_name, sm);
2663 } END_FOR_EACH_SM(sm);
2665 /* always print returned states after processing param states */
2666 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2667 param = get_return_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2668 if (param != -1 || !printed_name)
2669 continue;
2670 cb->callback(return_id, return_ranges, expr, -1, printed_name, sm);
2671 } END_FOR_EACH_SM(sm);
2674 static void print_return_info(int return_id, char *return_ranges, struct expression *expr)
2676 struct return_info_callback *cb;
2677 struct expression *tmp;
2678 struct symbol *sym;
2680 if (!option_info && !__inline_fn &&
2681 !local_debug && !option_debug)
2682 return;
2684 tmp = get_fake_variable(expr);
2685 if (tmp)
2686 expr = tmp;
2687 sym = expr_to_sym(expr);
2689 FOR_EACH_PTR(return_callbacks, cb) {
2690 __ignore_param_used++;
2691 print_return_struct_info(return_id, return_ranges, expr, sym, cb);
2692 __ignore_param_used--;
2693 } END_FOR_EACH_PTR(cb);
2696 static void reset_memdb(struct symbol *sym)
2698 mem_sql(NULL, NULL, "delete from caller_info;");
2699 mem_sql(NULL, NULL, "delete from return_states;");
2700 mem_sql(NULL, NULL, "delete from call_implies;");
2701 mem_sql(NULL, NULL, "delete from return_implies;");
2704 static void match_end_func_info(struct symbol *sym)
2706 if (__path_is_null())
2707 return;
2708 call_return_state_hooks(NULL);
2711 static void match_after_func(struct symbol *sym)
2713 clear_cached_return_vals();
2714 if (!__inline_fn)
2715 reset_memdb(sym);
2718 static void init_memdb(void)
2720 char *err = NULL;
2721 int rc;
2722 const char *schema_files[] = {
2723 "db/db.schema",
2724 "db/caller_info.schema",
2725 "db/common_caller_info.schema",
2726 "db/return_states.schema",
2727 "db/function_type_size.schema",
2728 "db/type_size.schema",
2729 "db/function_type_info.schema",
2730 "db/type_info.schema",
2731 "db/call_implies.schema",
2732 "db/return_implies.schema",
2733 "db/function_ptr.schema",
2734 "db/local_values.schema",
2735 "db/function_type_value.schema",
2736 "db/type_value.schema",
2737 "db/function_type.schema",
2738 "db/data_info.schema",
2739 "db/parameter_name.schema",
2740 "db/constraints.schema",
2741 "db/constraints_required.schema",
2742 "db/fn_ptr_data_link.schema",
2743 "db/fn_data_link.schema",
2744 "db/mtag_about.schema",
2745 "db/mtag_info.schema",
2746 "db/mtag_map.schema",
2747 "db/mtag_data.schema",
2748 "db/mtag_alias.schema",
2750 static char buf[4096];
2751 int fd;
2752 int ret;
2753 int i;
2755 rc = sqlite3_open(":memory:", &mem_db);
2756 if (rc != SQLITE_OK) {
2757 sm_ierror("starting In-Memory database.");
2758 return;
2761 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2762 fd = open_schema_file(schema_files[i]);
2763 if (fd < 0)
2764 continue;
2765 ret = read(fd, buf, sizeof(buf));
2766 if (ret < 0) {
2767 sm_ierror("failed to read: %s", schema_files[i]);
2768 continue;
2770 close(fd);
2771 if (ret == sizeof(buf)) {
2772 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2773 schema_files[i], sizeof(buf));
2774 continue;
2776 buf[ret] = '\0';
2777 rc = sqlite3_exec(mem_db, buf, NULL, NULL, &err);
2778 if (rc != SQLITE_OK) {
2779 sm_ierror("SQL error #2: %s", err);
2780 sm_ierror("%s", buf);
2785 static void init_cachedb(void)
2787 char *err = NULL;
2788 int rc;
2789 const char *schema_files[] = {
2790 "db/call_implies.schema",
2791 "db/return_implies.schema",
2792 "db/type_info.schema",
2793 "db/mtag_about.schema",
2794 "db/mtag_data.schema",
2795 "db/mtag_info.schema",
2796 "db/sink_info.schema",
2797 "db/hash_string.schema",
2799 static char buf[4096];
2800 int fd;
2801 int ret;
2802 int i;
2804 rc = sqlite3_open(":memory:", &cache_db);
2805 if (rc != SQLITE_OK) {
2806 sm_ierror("starting In-Memory database.");
2807 return;
2810 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2811 fd = open_schema_file(schema_files[i]);
2812 if (fd < 0)
2813 continue;
2814 ret = read(fd, buf, sizeof(buf));
2815 if (ret < 0) {
2816 sm_ierror("failed to read: %s", schema_files[i]);
2817 continue;
2819 close(fd);
2820 if (ret == sizeof(buf)) {
2821 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2822 schema_files[i], sizeof(buf));
2823 continue;
2825 buf[ret] = '\0';
2826 rc = sqlite3_exec(cache_db, buf, NULL, NULL, &err);
2827 if (rc != SQLITE_OK) {
2828 sm_ierror("SQL error #2: %s", err);
2829 sm_ierror("%s", buf);
2834 static int save_cache_data(void *_table, int argc, char **argv, char **azColName)
2836 static char buf[4096];
2837 char tmp[256];
2838 char *p = buf;
2839 char *table = _table;
2840 int i;
2843 p += snprintf(p, 4096 - (p - buf), "insert or ignore into %s values (", table);
2844 for (i = 0; i < argc; i++) {
2845 if (i)
2846 p += snprintf(p, 4096 - (p - buf), ", ");
2847 sqlite3_snprintf(sizeof(tmp), tmp, "%q", escape_newlines(argv[i]));
2848 p += snprintf(p, 4096 - (p - buf), "'%s'", tmp);
2851 p += snprintf(p, 4096 - (p - buf), ");");
2852 if (p - buf > 4096)
2853 return 0;
2855 sm_msg("SQL: %s", buf);
2856 return 0;
2859 static void dump_cache(struct symbol_list *sym_list)
2861 const char *cache_tables[] = {
2862 "type_info", "return_implies", "call_implies", "mtag_data",
2863 "mtag_info", "mtag_about", "sink_info", "hash_string",
2865 char buf[64];
2866 int i;
2868 if (!option_info)
2869 return;
2871 for (i = 0; i < ARRAY_SIZE(cache_tables); i++) {
2872 snprintf(buf, sizeof(buf), "select * from %s;", cache_tables[i]);
2873 cache_sql(&save_cache_data, (char *)cache_tables[i], buf);
2877 void open_smatch_db(char *db_file)
2879 int rc;
2881 if (option_no_db)
2882 return;
2884 use_states = malloc(num_checks);
2885 memset(use_states, 0xff, num_checks);
2887 init_memdb();
2888 init_cachedb();
2890 rc = sqlite3_open_v2(db_file, &smatch_db, SQLITE_OPEN_READONLY, NULL);
2891 if (rc != SQLITE_OK) {
2892 option_no_db = 1;
2893 return;
2895 run_sql(NULL, NULL,
2896 "PRAGMA cache_size = %d;", SQLITE_CACHE_PAGES);
2897 return;
2900 static char *get_next_string(char **str)
2902 static char string[256];
2903 char *start;
2904 char *p = *str;
2905 int len, i, j;
2907 if (*p == '\0')
2908 return NULL;
2909 start = p;
2911 while (*p != '\0' && *p != '\n') {
2912 if (*p == '\\' && *(p + 1) == ' ') {
2913 p += 2;
2914 continue;
2916 if (*p == ' ')
2917 break;
2918 p++;
2921 len = p - start;
2922 if (len >= sizeof(string)) {
2923 memcpy(string, start, sizeof(string));
2924 string[sizeof(string) - 1] = '\0';
2925 sm_ierror("return_fix: '%s' too long", string);
2926 **str = '\0';
2927 return NULL;
2929 memcpy(string, start, len);
2930 string[len] = '\0';
2931 for (i = 0; i < sizeof(string) - 1; i++) {
2932 if (string[i] == '\\' && string[i + 1] == ' ') {
2933 for (j = i; string[j] != '\0'; j++)
2934 string[j] = string[j + 1];
2937 if (*p != '\0')
2938 p++;
2939 *str = p;
2940 return string;
2943 static void register_return_deletes(void)
2945 char *func, *ret_str;
2946 char filename[256];
2947 char buf[4096];
2948 int fd, ret, i;
2949 char *p;
2951 snprintf(filename, 256, "db/%s.delete.return_states", option_project_str);
2952 fd = open_schema_file(filename);
2953 if (fd < 0)
2954 return;
2955 ret = read(fd, buf, sizeof(buf));
2956 close(fd);
2957 if (ret < 0)
2958 return;
2959 if (ret == sizeof(buf)) {
2960 sm_ierror("file too large: %s (limit %zd bytes)",
2961 filename, sizeof(buf));
2962 return;
2964 buf[ret] = '\0';
2966 p = buf;
2967 while (*p) {
2968 get_next_string(&p);
2969 delete_count++;
2971 if (delete_count == 0)
2972 return;
2973 if (delete_count % 2 != 0) {
2974 printf("error parsing '%s' delete_count=%d\n", filename, delete_count);
2975 delete_count = 0;
2976 return;
2978 delete_table = malloc(delete_count * sizeof(char *));
2980 p = buf;
2981 i = 0;
2982 while (*p) {
2983 func = alloc_string(get_next_string(&p));
2984 ret_str = alloc_string(get_next_string(&p));
2986 delete_table[i++] = func;
2987 delete_table[i++] = ret_str;
2991 #define RETURN_FIX_SIZE 8196
2992 static void register_return_replacements(void)
2994 char *func, *orig, *new;
2995 char filename[256];
2996 int fd, ret, i;
2997 char *buf;
2998 char *p;
3000 snprintf(filename, 256, "db/%s.return_fixes", option_project_str);
3001 fd = open_schema_file(filename);
3002 if (fd < 0)
3003 return;
3004 buf = malloc(RETURN_FIX_SIZE);
3005 ret = read(fd, buf, RETURN_FIX_SIZE);
3006 close(fd);
3007 if (ret < 0) {
3008 free(buf);
3009 return;
3011 if (ret == RETURN_FIX_SIZE) {
3012 sm_ierror("file too large: %s (limit %d bytes)",
3013 filename, RETURN_FIX_SIZE);
3014 free(buf);
3015 return;
3017 buf[ret] = '\0';
3019 p = buf;
3020 while (*p) {
3021 get_next_string(&p);
3022 replace_count++;
3024 if (replace_count == 0) {
3025 free(buf);
3026 return;
3028 if (replace_count % 3 != 0) {
3029 printf("error parsing '%s' replace_count=%d\n", filename, replace_count);
3030 replace_count = 0;
3031 free(buf);
3032 return;
3034 replace_table = malloc(replace_count * sizeof(char *));
3036 p = buf;
3037 i = 0;
3038 while (*p) {
3039 func = alloc_string(get_next_string(&p));
3040 orig = alloc_string(get_next_string(&p));
3041 new = alloc_string(get_next_string(&p));
3043 replace_table[i++] = func;
3044 replace_table[i++] = orig;
3045 replace_table[i++] = new;
3047 free(buf);
3050 static void register_forced_return_splits(void)
3052 int struct_members = sizeof(struct split_data) / sizeof(char *);
3053 char filename[256];
3054 char buf[4096];
3055 int fd, ret, i;
3056 char *p;
3058 snprintf(filename, 256, "db/%s.forced_return_splits", option_project_str);
3059 fd = open_schema_file(filename);
3060 if (fd < 0)
3061 return;
3062 ret = read(fd, buf, sizeof(buf));
3063 close(fd);
3064 if (ret < 0)
3065 return;
3066 if (ret == sizeof(buf)) {
3067 sm_ierror("file too large: %s (limit %zd bytes)",
3068 filename, sizeof(buf));
3069 return;
3071 buf[ret] = '\0';
3073 p = buf;
3074 while (*p) {
3075 get_next_string(&p);
3076 split_count++;
3078 if (split_count == 0)
3079 return;
3080 if (split_count % struct_members != 0) {
3081 printf("error parsing '%s' split_count=%d\n", filename, split_count);
3082 split_count = 0;
3083 return;
3085 split_count /= struct_members;
3086 forced_splits = malloc(split_count * sizeof(void *));
3088 p = buf;
3089 i = 0;
3090 while (*p) {
3091 struct split_data *split = malloc(sizeof(*split));
3093 split->func = alloc_string(get_next_string(&p));
3094 split->rl = alloc_string(get_next_string(&p));
3095 forced_splits[i++] = split;
3099 void register_definition_db_callbacks(int id)
3101 my_id = id;
3103 add_hook(&match_call_info, FUNCTION_CALL_HOOK_BEFORE);
3104 add_hook(&match_call_info_new, FUNCTION_CALL_HOOK_BEFORE);
3105 add_split_return_callback(match_return_info);
3106 add_split_return_callback(print_returned_struct_members);
3107 add_split_return_callback(print_return_info);
3108 add_hook(&call_return_state_hooks, RETURN_HOOK);
3109 add_hook(&match_end_func_info, END_FUNC_HOOK);
3110 add_hook(&match_after_func, AFTER_FUNC_HOOK);
3112 add_hook(&match_data_from_db, FUNC_DEF_HOOK);
3113 add_hook(&match_call_implies, FUNC_DEF_HOOK);
3114 add_hook(&match_return_implies_early, CALL_HOOK_AFTER_INLINE);
3116 common_funcs = load_strings_from_file(option_project_str, "common_functions");
3117 register_return_deletes();
3118 register_return_replacements();
3119 register_forced_return_splits();
3121 add_hook(&dump_cache, END_FILE_HOOK);
3124 void register_definition_db_callbacks_late(int id)
3126 add_hook(&match_return_implies_late, CALL_HOOK_AFTER_INLINE);
3129 void register_db_call_marker(int id)
3131 add_hook(&match_call_marker, FUNCTION_CALL_HOOK_BEFORE);
3134 char *get_data_info_name(struct expression *expr)
3136 struct symbol *sym;
3137 char *name;
3138 char buf[256];
3139 char *ret = NULL;
3141 expr = strip_expr(expr);
3142 name = get_member_name(expr);
3143 if (name)
3144 return name;
3145 name = expr_to_var_sym(expr, &sym);
3146 if (!name || !sym)
3147 goto free;
3148 if (!(sym->ctype.modifiers & MOD_TOPLEVEL))
3149 goto free;
3150 if (sym->ctype.modifiers & MOD_STATIC)
3151 snprintf(buf, sizeof(buf), "static %s", name);
3152 else
3153 snprintf(buf, sizeof(buf), "global %s", name);
3154 ret = alloc_sname(buf);
3155 free:
3156 free_string(name);
3157 return ret;