kernel.return_fixes: add mipi_dsi_device_transfer(), timer_delete() and get_device()
[smatch.git] / smatch_db.c
blobef5146abaaacac098641f546c67d4060a29d6fd5
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 char line_number[16];
1732 snprintf(line_number, sizeof(line_number), "%d", get_lineno());
1733 sql_insert_return_states(return_id, return_ranges, INTERNAL, -1, line_number, function_signature());
1736 static bool call_return_state_hooks_conditional(struct expression *expr)
1738 int final_pass_orig = final_pass;
1739 static int recurse;
1741 if (recurse >= 2)
1742 return false;
1743 if (!expr ||
1744 (expr->type != EXPR_CONDITIONAL && expr->type != EXPR_SELECT))
1745 return false;
1747 recurse++;
1749 __push_fake_cur_stree();
1751 final_pass = 0;
1752 __split_whole_condition(expr->conditional);
1753 final_pass = final_pass_orig;
1755 call_return_state_hooks(expr->cond_true ?: expr->conditional);
1757 __push_true_states();
1758 __use_false_states();
1760 call_return_state_hooks(expr->cond_false);
1762 __merge_true_states();
1763 __free_fake_cur_stree();
1765 recurse--;
1766 return true;
1769 static bool handle_forced_split(const char *return_ranges, struct expression *expr)
1771 struct split_data *data = NULL;
1772 struct expression *compare;
1773 struct range_list *rl;
1774 char buf[64];
1775 char *math;
1776 sval_t sval;
1777 bool undo;
1778 int i;
1780 for (i = 0; i < split_count; i++) {
1781 if (get_function() &&
1782 strcmp(get_function(), forced_splits[i]->func) == 0) {
1783 data = forced_splits[i];
1784 break;
1787 if (!data)
1788 return false;
1790 // FIXME: this works for copy_to/from_user() because the only thing we
1791 // care about is zero/non-zero
1792 if (strcmp(data->rl, "0") != 0)
1793 return false;
1795 compare = compare_expression(expr, SPECIAL_EQUAL, zero_expr());
1796 if (!compare)
1797 return false;
1798 if (get_implied_value(compare, &sval))
1799 return false;
1801 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
1802 call_return_states_callbacks("0", expr);
1803 if (undo)
1804 end_assume();
1806 undo = assume(compare_expression(expr, SPECIAL_NOTEQUAL, zero_expr()));
1807 if (get_implied_rl(expr, &rl)) {
1808 math = strchr(return_ranges, '[');
1809 snprintf(buf, sizeof(buf), "%s%s", show_rl(rl), math ?: "");
1810 } else {
1811 snprintf(buf, sizeof(buf), "%s", return_ranges);
1813 call_return_states_callbacks(buf, expr);
1814 if (undo)
1815 end_assume();
1817 return true;
1820 static void call_return_states_callbacks(const char *return_ranges, struct expression *expr)
1822 struct returned_state_callback *cb;
1824 return_ranges = replace_return_ranges(return_ranges);
1825 if (is_delete_return(return_ranges))
1826 return;
1827 if (is_project_delete_return(expr))
1828 return;
1829 if (handle_forced_split(return_ranges, expr))
1830 return;
1832 return_id++;
1833 FOR_EACH_PTR(returned_state_callbacks, cb) {
1834 cb->callback(return_id, (char *)return_ranges, expr);
1835 } END_FOR_EACH_PTR(cb);
1838 static void call_return_state_hooks_compare(struct expression *expr)
1840 char *return_ranges;
1841 int final_pass_orig = final_pass;
1842 sval_t sval = { .type = &int_ctype };
1843 sval_t ret;
1845 if (!get_implied_value(expr, &ret))
1846 ret.value = -1;
1848 __push_fake_cur_stree();
1850 final_pass = 0;
1851 __split_whole_condition(expr);
1852 final_pass = final_pass_orig;
1854 if (ret.value != 0) {
1855 return_ranges = alloc_sname("1");
1856 sval.value = 1;
1857 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1859 call_return_states_callbacks(return_ranges, expr);
1862 __push_true_states();
1863 __use_false_states();
1865 if (ret.value != 1) {
1866 return_ranges = alloc_sname("0");
1867 sval.value = 0;
1868 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1870 call_return_states_callbacks(return_ranges, expr);
1873 __merge_true_states();
1874 __free_fake_cur_stree();
1877 static bool is_implies_function(struct expression *expr)
1879 struct range_list *rl;
1881 if (!expr)
1882 return false;
1884 rl = get_range_implications(get_function());
1885 if (!rl)
1886 return false;
1888 sm_msg("%s: is implied", __func__);
1889 return true;
1892 static int ptr_in_list(struct sm_state *sm, struct state_list *slist)
1894 struct sm_state *tmp;
1896 FOR_EACH_PTR(slist, tmp) {
1897 if (strcmp(tmp->state->name, sm->state->name) == 0)
1898 return 1;
1899 } END_FOR_EACH_PTR(tmp);
1901 return 0;
1904 static int split_possible_helper(struct sm_state *sm, struct expression *expr)
1906 struct range_list *rl;
1907 char *return_ranges;
1908 struct sm_state *tmp;
1909 int ret = 0;
1910 int nr_possible, nr_states;
1911 char *compare_str;
1912 char buf[128];
1913 struct state_list *already_handled = NULL;
1914 sval_t sval;
1916 if (!sm || !sm->merged)
1917 return 0;
1919 if (too_many_possible(sm) && !is_implies_function(expr))
1920 return 0;
1922 /* bail if it gets too complicated */
1923 nr_possible = 0;
1924 FOR_EACH_PTR(sm->possible, tmp) {
1925 if (!is_leaf(tmp))
1926 continue;
1927 if (ptr_in_list(tmp, already_handled))
1928 continue;
1929 add_ptr_list(&already_handled, tmp);
1930 nr_possible++;
1931 } END_FOR_EACH_PTR(tmp);
1932 free_slist(&already_handled);
1933 nr_states = get_db_state_count();
1934 if (nr_states * nr_possible >= 2000 && !is_implies_function(expr))
1935 return 0;
1937 FOR_EACH_PTR(sm->possible, tmp) {
1938 if (!is_leaf(tmp))
1939 continue;
1940 if (ptr_in_list(tmp, already_handled))
1941 continue;
1942 add_ptr_list(&already_handled, tmp);
1944 ret = 1;
1945 __push_fake_cur_stree();
1947 overwrite_states_using_pool(sm, tmp);
1949 rl = cast_rl(cur_func_return_type(), estate_rl(tmp->state));
1950 return_ranges = show_rl(rl);
1951 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(clone_rl(rl)));
1952 compare_str = get_return_compare_str(expr);
1953 /* ignore obvious stuff like 0 <= param */
1954 /* Is this worthile when we have PARAM_COMPARE? */
1955 if (compare_str &&
1956 strncmp(compare_str, "[=", 2) != 0 &&
1957 rl_to_sval(rl, &sval))
1958 compare_str = NULL;
1959 if (compare_str) {
1960 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1961 return_ranges = alloc_sname(buf);
1964 call_return_states_callbacks(return_ranges, expr);
1966 __free_fake_cur_stree();
1967 } END_FOR_EACH_PTR(tmp);
1969 free_slist(&already_handled);
1971 return ret;
1974 static int call_return_state_hooks_split_possible(struct expression *expr)
1976 struct sm_state *sm;
1978 if (!expr)
1979 return 0;
1981 sm = get_returned_sm(expr);
1982 return split_possible_helper(sm, expr);
1985 static bool has_empty_state(struct sm_state *sm)
1987 struct sm_state *tmp;
1989 FOR_EACH_PTR(sm->possible, tmp) {
1990 if (!estate_rl(tmp->state))
1991 return true;
1992 } END_FOR_EACH_PTR(tmp);
1994 return false;
1997 static bool has_possible_negative(struct sm_state *sm)
1999 struct sm_state *tmp;
2001 if (!type_signed(estate_type(sm->state)))
2002 return false;
2004 FOR_EACH_PTR(sm->possible, tmp) {
2005 if (!estate_rl(tmp->state))
2006 continue;
2007 if (sval_is_negative(estate_min(tmp->state)) &&
2008 sval_is_negative(estate_max(tmp->state)))
2009 return true;
2010 } END_FOR_EACH_PTR(tmp);
2012 return false;
2015 static bool has_separate_zero_null(struct sm_state *sm)
2017 struct sm_state *tmp;
2018 sval_t sval;
2020 FOR_EACH_PTR(sm->possible, tmp) {
2021 if (!estate_get_single_value(tmp->state, &sval))
2022 continue;
2023 if (sval.value == 0)
2024 return true;
2025 } END_FOR_EACH_PTR(tmp);
2027 return false;
2030 static int split_positive_from_negative(struct expression *expr)
2032 struct sm_state *sm;
2033 struct range_list *rl;
2034 const char *return_ranges;
2035 struct range_list *ret_rl;
2036 bool separate_zero;
2037 int undo;
2039 /* We're going to print the states 3 times */
2040 if (get_db_state_count() > 10000 / 3)
2041 return 0;
2043 if (!get_implied_rl(expr, &rl) || !rl)
2044 return 0;
2045 /* Forget about INT_MAX and larger */
2046 if (rl_max(rl).value <= 0)
2047 return 0;
2048 if (!sval_is_negative(rl_min(rl)))
2049 return 0;
2051 sm = get_returned_sm(expr);
2052 if (!sm)
2053 return 0;
2054 if (has_empty_state(sm))
2055 return 0;
2056 if (!has_possible_negative(sm))
2057 return 0;
2058 separate_zero = has_separate_zero_null(sm);
2060 if (!assume(compare_expression(expr, separate_zero ? '>' : SPECIAL_GTE, zero_expr())))
2061 return 0;
2063 return_ranges = get_return_ranges_str(expr, &ret_rl);
2064 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2065 call_return_states_callbacks(return_ranges, expr);
2067 end_assume();
2069 if (separate_zero) {
2070 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
2072 return_ranges = get_return_ranges_str(expr, &ret_rl);
2073 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2074 call_return_states_callbacks(return_ranges, expr);
2076 if (undo)
2077 end_assume();
2080 undo = assume(compare_expression(expr, '<', zero_expr()));
2082 return_ranges = get_return_ranges_str(expr, &ret_rl);
2083 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2084 call_return_states_callbacks(return_ranges, expr);
2086 if (undo)
2087 end_assume();
2089 return 1;
2092 static int call_return_state_hooks_split_null_non_null_zero(struct expression *expr)
2094 struct range_list *rl;
2095 struct range_list *nonnull_rl;
2096 sval_t null_sval;
2097 struct range_list *null_rl = NULL;
2098 char *return_ranges;
2099 struct sm_state *sm;
2100 struct smatch_state *state;
2101 int nr_states;
2102 int final_pass_orig = final_pass;
2104 if (!expr || expr_equal_to_param(expr, -1))
2105 return 0;
2106 if (expr->type == EXPR_CALL)
2107 return 0;
2109 sm = get_returned_sm(expr);
2110 if (!sm)
2111 return 0;
2112 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2113 return 0;
2114 state = sm->state;
2115 if (!estate_rl(state))
2116 return 0;
2117 if (estate_min(state).value == 0 && estate_max(state).value == 0)
2118 return 0;
2119 if (has_possible_negative(sm))
2120 return 0;
2121 if (!has_separate_zero_null(sm))
2122 return 0;
2124 nr_states = get_db_state_count();
2125 if (option_info && nr_states >= 1500)
2126 return 0;
2128 rl = estate_rl(state);
2130 __push_fake_cur_stree();
2132 final_pass = 0;
2133 __split_whole_condition(expr);
2134 final_pass = final_pass_orig;
2136 nonnull_rl = rl_filter(rl, rl_zero());
2137 return_ranges = show_rl(nonnull_rl);
2138 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonnull_rl));
2140 call_return_states_callbacks(return_ranges, expr);
2142 __push_true_states();
2143 __use_false_states();
2145 return_ranges = alloc_sname("0");
2146 null_sval = sval_type_val(rl_type(rl), 0);
2147 add_range(&null_rl, null_sval, null_sval);
2148 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(null_rl));
2149 call_return_states_callbacks(return_ranges, expr);
2151 __merge_true_states();
2152 __free_fake_cur_stree();
2154 return 1;
2157 static bool is_neg_and_pos_err_code(struct range_list *rl)
2159 struct data_range *tmp, *last;
2161 if (option_project != PROJ_KERNEL)
2162 return false;
2163 if (!rl)
2164 return false;
2166 /* Assume s32min-(14),(-12)-(-1),1-s32max is an error code. */
2167 last = last_ptr_list((struct ptr_list *)rl);
2168 if (last->max.value >= 0 &&
2169 (last->min.value != 1 ||
2170 last->max.value != INT_MAX))
2171 return false;
2174 FOR_EACH_PTR(rl, tmp) {
2175 if (tmp == last)
2176 break;
2177 if (tmp->min.value != INT_MIN && tmp->min.value < -4095)
2178 return false;
2179 if (tmp->max.value < -4095 || tmp->max.value >= 0)
2180 return false;
2181 } END_FOR_EACH_PTR(tmp);
2183 return true;
2186 static bool is_kernel_success_fail(struct sm_state *sm)
2188 struct sm_state *tmp;
2189 struct range_list *rl;
2190 bool has_zero = false;
2191 bool has_neg = false;
2193 if (!sm)
2194 return false;
2196 if (!type_signed(estate_type(sm->state)))
2197 return false;
2199 FOR_EACH_PTR(sm->possible, tmp) {
2200 rl = estate_rl(tmp->state);
2201 if (!rl)
2202 return false;
2203 if (!is_leaf(tmp))
2204 continue;
2205 if (rl_min(rl).value == 0 && rl_max(rl).value == 0) {
2206 has_zero = true;
2207 continue;
2209 has_neg = true;
2210 if (is_neg_and_pos_err_code(estate_rl(tmp->state)))
2211 continue;
2212 return false;
2213 } END_FOR_EACH_PTR(tmp);
2215 return has_zero && has_neg;
2218 static int call_return_state_hooks_split_success_fail(struct expression *expr)
2220 struct expression *tmp_ret;
2221 struct sm_state *sm;
2222 struct range_list *rl;
2223 struct range_list *nonzero_rl;
2224 sval_t zero_sval;
2225 struct range_list *zero_rl = NULL;
2226 int nr_states;
2227 char *return_ranges;
2228 int final_pass_orig = final_pass;
2230 if (option_project != PROJ_KERNEL)
2231 return 0;
2233 nr_states = get_db_state_count();
2234 if (nr_states > 2000)
2235 return 0;
2237 tmp_ret = get_fake_variable(expr);
2238 if (!tmp_ret)
2239 tmp_ret = expr;
2240 sm = get_returned_sm(tmp_ret);
2241 if (!sm)
2242 return 0;
2243 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2244 return 0;
2245 if (!is_kernel_success_fail(sm))
2246 return 0;
2248 rl = estate_rl(sm->state);
2249 if (!rl)
2250 return 0;
2252 __push_fake_cur_stree();
2254 final_pass = 0;
2255 __split_whole_condition(tmp_ret);
2256 final_pass = final_pass_orig;
2258 nonzero_rl = rl_filter(rl, rl_zero());
2259 nonzero_rl = cast_rl(cur_func_return_type(), nonzero_rl);
2260 return_ranges = show_rl(nonzero_rl);
2261 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonzero_rl));
2263 call_return_states_callbacks(return_ranges, expr);
2265 __push_true_states();
2266 __use_false_states();
2268 return_ranges = alloc_sname("0");
2269 zero_sval = sval_type_val(rl_type(rl), 0);
2270 add_range(&zero_rl, zero_sval, zero_sval);
2271 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(zero_rl));
2272 call_return_states_callbacks(return_ranges, expr);
2274 __merge_true_states();
2275 __free_fake_cur_stree();
2277 return 1;
2280 static int is_boolean(struct expression *expr)
2282 struct range_list *rl;
2284 if (!get_implied_rl(expr, &rl))
2285 return 0;
2286 if (rl_min(rl).value == 0 && rl_max(rl).value == 1)
2287 return 1;
2288 return 0;
2291 static int splitable_function_call(struct expression *expr)
2293 struct sm_state *sm;
2295 if (!expr || expr->type != EXPR_CALL)
2296 return 0;
2297 sm = get_extra_sm_state(expr);
2298 return split_possible_helper(sm, expr);
2301 static struct sm_state *find_bool_param(void)
2303 struct stree *start_states;
2304 struct symbol *arg;
2305 struct sm_state *sm, *tmp;
2306 sval_t sval;
2308 start_states = get_start_states();
2310 FOR_EACH_PTR_REVERSE(cur_func_sym->ctype.base_type->arguments, arg) {
2311 if (!arg->ident)
2312 continue;
2313 sm = get_sm_state_stree(start_states, SMATCH_EXTRA, arg->ident->name, arg);
2314 if (!sm)
2315 continue;
2316 if (rl_min(estate_rl(sm->state)).value != 0 ||
2317 rl_max(estate_rl(sm->state)).value != 1)
2318 continue;
2319 goto found;
2320 } END_FOR_EACH_PTR_REVERSE(arg);
2322 return NULL;
2324 found:
2326 * Check if it's splitable. If not, then splitting it up is likely not
2327 * useful for the callers.
2329 FOR_EACH_PTR(sm->possible, tmp) {
2330 if (is_merged(tmp))
2331 continue;
2332 if (!estate_get_single_value(tmp->state, &sval))
2333 return NULL;
2334 } END_FOR_EACH_PTR(tmp);
2336 return sm;
2339 static int split_on_bool_sm(struct sm_state *sm, struct expression *expr)
2341 struct range_list *ret_rl;
2342 const char *return_ranges;
2343 struct sm_state *tmp;
2344 int ret = 0;
2345 struct state_list *already_handled = NULL;
2347 if (!sm || !sm->merged)
2348 return 0;
2350 if (too_many_possible(sm))
2351 return 0;
2353 FOR_EACH_PTR(sm->possible, tmp) {
2354 if (!is_leaf(tmp))
2355 continue;
2356 if (ptr_in_list(tmp, already_handled))
2357 continue;
2358 add_ptr_list(&already_handled, tmp);
2360 ret = 1;
2361 __push_fake_cur_stree();
2363 overwrite_states_using_pool(sm, tmp);
2365 return_ranges = get_return_ranges_str(expr, &ret_rl);
2366 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2367 call_return_states_callbacks(return_ranges, expr);
2369 __free_fake_cur_stree();
2370 } END_FOR_EACH_PTR(tmp);
2372 free_slist(&already_handled);
2374 return ret;
2377 static int split_by_bool_param(struct expression *expr)
2379 struct sm_state *start_sm, *sm;
2380 sval_t sval;
2382 start_sm = find_bool_param();
2383 if (!start_sm)
2384 return 0;
2385 sm = get_sm_state(SMATCH_EXTRA, start_sm->name, start_sm->sym);
2386 if (!sm || estate_get_single_value(sm->state, &sval))
2387 return 0;
2389 if (get_db_state_count() * 2 >= 2000)
2390 return 0;
2392 return split_on_bool_sm(sm, expr);
2395 static int split_by_null_nonnull_param(struct expression *expr)
2397 struct symbol *arg;
2398 struct sm_state *sm;
2399 int nr_possible;
2401 arg = first_ptr_list((struct ptr_list *)cur_func_sym->ctype.base_type->arguments);
2402 if (!arg || !arg->ident)
2403 return 0;
2404 if (get_real_base_type(arg)->type != SYM_PTR)
2405 return 0;
2407 if (param_was_set_var_sym(arg->ident->name, arg))
2408 return 0;
2409 sm = get_sm_state(SMATCH_EXTRA, arg->ident->name, arg);
2410 if (!sm)
2411 return 0;
2413 if (!has_separate_zero_null(sm))
2414 return 0;
2416 nr_possible = ptr_list_size((struct ptr_list *)sm->possible);
2417 if (get_db_state_count() * nr_possible >= 2000)
2418 return 0;
2420 return split_on_bool_sm(sm, expr);
2423 static void call_hooks_based_on_pool(struct expression *expr, struct sm_state *gate_sm, struct sm_state *pool_sm)
2425 struct range_list *ret_rl;
2426 const char *return_ranges;
2428 __push_fake_cur_stree();
2430 overwrite_states_using_pool(gate_sm, pool_sm);
2432 return_ranges = get_return_ranges_str(expr, &ret_rl);
2433 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2434 call_return_states_callbacks(return_ranges, expr);
2436 __free_fake_cur_stree();
2439 static bool split_by_impossible(struct expression *expr)
2441 static int impossible_id;
2442 struct sm_state *sm, *tmp;
2443 int nr_states;
2445 if (!impossible_id)
2446 impossible_id = id_from_name("register_impossible_return");
2447 if (!impossible_id)
2448 return false;
2451 * The only states for register_impossible_return are &impossible,
2452 * &undefined and &merged. This function will break otherwise.
2455 sm = get_sm_state(impossible_id, "impossible", NULL);
2456 if (!sm || sm->state != &merged)
2457 return false;
2459 nr_states = get_db_state_count();
2460 if (nr_states >= 1000)
2461 return false;
2463 /* handle possible */
2464 FOR_EACH_PTR(sm->possible, tmp) {
2465 if (!is_leaf(tmp))
2466 continue;
2467 if (tmp->state != &undefined)
2468 continue;
2469 call_hooks_based_on_pool(expr, sm, tmp);
2470 goto impossible;
2471 } END_FOR_EACH_PTR(tmp);
2473 impossible:
2474 /* handle impossible */
2475 FOR_EACH_PTR(sm->possible, tmp) {
2476 if (!is_leaf(tmp))
2477 continue;
2478 if (strcmp(tmp->state->name, "impossible") != 0)
2479 continue;
2480 call_hooks_based_on_pool(expr, sm, tmp);
2481 return true;
2482 } END_FOR_EACH_PTR(tmp);
2484 return false;
2487 struct expression *strip_expr_statement(struct expression *expr)
2489 struct expression *orig = expr;
2490 struct statement *stmt, *last_stmt;
2492 if (!expr)
2493 return NULL;
2494 if (expr->type == EXPR_PREOP && expr->op == '(')
2495 expr = expr->unop;
2496 if (expr->type != EXPR_STATEMENT)
2497 return orig;
2498 stmt = expr->statement;
2499 if (!stmt || stmt->type != STMT_COMPOUND)
2500 return orig;
2502 last_stmt = last_ptr_list((struct ptr_list *)stmt->stmts);
2503 if (!last_stmt || last_stmt->type == STMT_LABEL)
2504 last_stmt = last_stmt->label_statement;
2505 if (!last_stmt || last_stmt->type != STMT_EXPRESSION)
2506 return orig;
2507 return strip_expr(last_stmt->expression);
2510 static bool is_kernel_error_path(struct expression *expr)
2512 struct range_list *rl;
2514 if (option_project != PROJ_KERNEL)
2515 return false;
2517 if (!get_implied_rl(expr, &rl))
2518 return false;
2519 if (rl_type(rl) != &int_ctype)
2520 return false;
2521 if (!is_neg_and_pos_err_code(rl))
2522 return false;
2523 return true;
2526 static void call_return_state_hooks(struct expression *expr)
2528 struct range_list *ret_rl;
2529 const char *return_ranges;
2530 int nr_states;
2531 sval_t sval;
2533 if (debug_db) {
2534 struct range_list *rl = NULL;
2536 get_absolute_rl(expr, &rl);
2537 sm_msg("RETURN: expr='%s' rl='%s' %lu states%s", expr_to_str(expr),
2538 show_rl(rl), stree_count(__get_cur_stree()),
2539 is_impossible_path() ? " (impossible path)" : "");
2542 if (__path_is_null())
2543 return;
2545 if (is_impossible_path())
2546 goto vanilla;
2548 if (expr && (expr->type == EXPR_COMPARE ||
2549 !get_implied_value(expr, &sval)) &&
2550 (is_condition(expr) || is_boolean(expr))) {
2551 call_return_state_hooks_compare(expr);
2552 if (debug_db)
2553 sm_msg("%s: bool", __func__);
2554 return;
2555 } else if (call_return_state_hooks_conditional(expr)) {
2556 if (debug_db)
2557 sm_msg("%s: condition", __func__);
2558 return;
2559 } else if (is_kernel_error_path(expr)) {
2560 if (debug_db)
2561 sm_msg("%s: kernel error path", __func__);
2562 goto vanilla;
2563 } else if (call_return_state_hooks_split_success_fail(expr)) {
2564 if (debug_db)
2565 sm_msg("%s: success_fail", __func__);
2566 return;
2567 } else if (call_return_state_hooks_split_possible(expr)) {
2568 if (debug_db)
2569 sm_msg("%s: split_possible", __func__);
2570 return;
2571 } else if (split_positive_from_negative(expr)) {
2572 if (debug_db)
2573 sm_msg("%s: positive negative", __func__);
2574 return;
2575 } else if (call_return_state_hooks_split_null_non_null_zero(expr)) {
2576 if (debug_db)
2577 sm_msg("%s: split zero non-zero", __func__);
2578 return;
2579 } else if (splitable_function_call(expr)) {
2580 if (debug_db)
2581 sm_msg("%s: split_function_call", __func__);
2582 return;
2583 } else if (split_by_bool_param(expr)) {
2584 if (debug_db)
2585 sm_msg("%s: bool param", __func__);
2586 return;
2587 } else if (split_by_null_nonnull_param(expr)) {
2588 if (debug_db)
2589 sm_msg("%s: null non-null param", __func__);
2590 return;
2591 } else if (split_by_impossible(expr)) {
2592 if (debug_db)
2593 sm_msg("%s: split by impossible", __func__);
2594 return;
2597 vanilla:
2598 return_ranges = get_return_ranges_str(expr, &ret_rl);
2599 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2601 nr_states = get_db_state_count();
2602 if (nr_states >= 10000) {
2603 return_id++;
2604 match_return_info(return_id, (char *)return_ranges, expr);
2605 print_limited_param_set(return_id, (char *)return_ranges, expr);
2606 mark_all_params_untracked(return_id, (char *)return_ranges, expr);
2607 return;
2609 call_return_states_callbacks(return_ranges, expr);
2610 if (debug_db)
2611 sm_msg("%s: vanilla", __func__);
2614 static void print_returned_struct_members(int return_id, char *return_ranges, struct expression *expr)
2616 struct returned_member_callback *cb;
2617 struct sm_state *sm;
2618 struct symbol *type;
2619 char *name;
2620 char member_name[256];
2621 int len;
2623 type = get_type(expr);
2624 if (!type || type->type != SYM_PTR)
2625 return;
2626 name = expr_to_var(expr);
2627 if (!name)
2628 return;
2630 len = strlen(name);
2631 FOR_EACH_PTR(returned_member_callbacks, cb) {
2632 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2633 if (sm->name[0] == '*' && strcmp(sm->name + 1, name) == 0) {
2634 strcpy(member_name, "*$");
2635 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2636 continue;
2638 if (strncmp(sm->name, name, len) != 0)
2639 continue;
2640 if (strncmp(sm->name + len, "->", 2) != 0)
2641 continue;
2642 snprintf(member_name, sizeof(member_name), "$%s", sm->name + len);
2643 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2644 } END_FOR_EACH_SM(sm);
2645 } END_FOR_EACH_PTR(cb);
2647 free_string(name);
2650 static void print_return_struct_info(int return_id, char *return_ranges,
2651 struct expression *expr,
2652 struct symbol *sym,
2653 struct return_info_callback *cb)
2655 struct sm_state *sm;
2656 const char *printed_name;
2657 int param;
2659 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2660 param = get_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2661 if (!printed_name)
2662 continue;
2663 if (param < 0)
2664 continue;
2665 cb->callback(return_id, return_ranges, expr, param, printed_name, sm);
2666 } END_FOR_EACH_SM(sm);
2668 /* always print returned states after processing param states */
2669 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2670 param = get_return_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2671 if (param != -1 || !printed_name)
2672 continue;
2673 cb->callback(return_id, return_ranges, expr, -1, printed_name, sm);
2674 } END_FOR_EACH_SM(sm);
2677 static void print_return_info(int return_id, char *return_ranges, struct expression *expr)
2679 struct return_info_callback *cb;
2680 struct expression *tmp;
2681 struct symbol *sym;
2683 if (!option_info && !__inline_fn &&
2684 !local_debug && !option_debug)
2685 return;
2687 tmp = get_fake_variable(expr);
2688 if (tmp)
2689 expr = tmp;
2690 sym = expr_to_sym(expr);
2692 FOR_EACH_PTR(return_callbacks, cb) {
2693 __ignore_param_used++;
2694 print_return_struct_info(return_id, return_ranges, expr, sym, cb);
2695 __ignore_param_used--;
2696 } END_FOR_EACH_PTR(cb);
2699 static void reset_memdb(struct symbol *sym)
2701 mem_sql(NULL, NULL, "delete from caller_info;");
2702 mem_sql(NULL, NULL, "delete from return_states;");
2703 mem_sql(NULL, NULL, "delete from call_implies;");
2704 mem_sql(NULL, NULL, "delete from return_implies;");
2707 static void match_end_func_info(struct symbol *sym)
2709 if (__path_is_null())
2710 return;
2711 call_return_state_hooks(NULL);
2714 static void match_after_func(struct symbol *sym)
2716 clear_cached_return_vals();
2717 if (!__inline_fn)
2718 reset_memdb(sym);
2721 static void init_memdb(void)
2723 char *err = NULL;
2724 int rc;
2725 const char *schema_files[] = {
2726 "db/db.schema",
2727 "db/caller_info.schema",
2728 "db/common_caller_info.schema",
2729 "db/return_states.schema",
2730 "db/function_type_size.schema",
2731 "db/type_size.schema",
2732 "db/function_type_info.schema",
2733 "db/type_info.schema",
2734 "db/call_implies.schema",
2735 "db/return_implies.schema",
2736 "db/function_ptr.schema",
2737 "db/local_values.schema",
2738 "db/function_type_value.schema",
2739 "db/type_value.schema",
2740 "db/function_type.schema",
2741 "db/data_info.schema",
2742 "db/parameter_name.schema",
2743 "db/constraints.schema",
2744 "db/constraints_required.schema",
2745 "db/fn_ptr_data_link.schema",
2746 "db/fn_data_link.schema",
2747 "db/mtag_about.schema",
2748 "db/mtag_info.schema",
2749 "db/mtag_map.schema",
2750 "db/mtag_data.schema",
2751 "db/mtag_alias.schema",
2753 static char buf[4096];
2754 int fd;
2755 int ret;
2756 int i;
2758 rc = sqlite3_open(":memory:", &mem_db);
2759 if (rc != SQLITE_OK) {
2760 sm_ierror("starting In-Memory database.");
2761 return;
2764 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2765 fd = open_schema_file(schema_files[i]);
2766 if (fd < 0)
2767 continue;
2768 ret = read(fd, buf, sizeof(buf));
2769 if (ret < 0) {
2770 sm_ierror("failed to read: %s", schema_files[i]);
2771 continue;
2773 close(fd);
2774 if (ret == sizeof(buf)) {
2775 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2776 schema_files[i], sizeof(buf));
2777 continue;
2779 buf[ret] = '\0';
2780 rc = sqlite3_exec(mem_db, buf, NULL, NULL, &err);
2781 if (rc != SQLITE_OK) {
2782 sm_ierror("SQL error #2: %s", err);
2783 sm_ierror("%s", buf);
2788 static void init_cachedb(void)
2790 char *err = NULL;
2791 int rc;
2792 const char *schema_files[] = {
2793 "db/call_implies.schema",
2794 "db/return_implies.schema",
2795 "db/type_info.schema",
2796 "db/mtag_about.schema",
2797 "db/mtag_data.schema",
2798 "db/mtag_info.schema",
2799 "db/sink_info.schema",
2800 "db/hash_string.schema",
2802 static char buf[4096];
2803 int fd;
2804 int ret;
2805 int i;
2807 rc = sqlite3_open(":memory:", &cache_db);
2808 if (rc != SQLITE_OK) {
2809 sm_ierror("starting In-Memory database.");
2810 return;
2813 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2814 fd = open_schema_file(schema_files[i]);
2815 if (fd < 0)
2816 continue;
2817 ret = read(fd, buf, sizeof(buf));
2818 if (ret < 0) {
2819 sm_ierror("failed to read: %s", schema_files[i]);
2820 continue;
2822 close(fd);
2823 if (ret == sizeof(buf)) {
2824 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2825 schema_files[i], sizeof(buf));
2826 continue;
2828 buf[ret] = '\0';
2829 rc = sqlite3_exec(cache_db, buf, NULL, NULL, &err);
2830 if (rc != SQLITE_OK) {
2831 sm_ierror("SQL error #2: %s", err);
2832 sm_ierror("%s", buf);
2837 static int save_cache_data(void *_table, int argc, char **argv, char **azColName)
2839 static char buf[4096];
2840 char tmp[256];
2841 char *p = buf;
2842 char *table = _table;
2843 int i;
2846 p += snprintf(p, 4096 - (p - buf), "insert or ignore into %s values (", table);
2847 for (i = 0; i < argc; i++) {
2848 if (i)
2849 p += snprintf(p, 4096 - (p - buf), ", ");
2850 sqlite3_snprintf(sizeof(tmp), tmp, "%q", escape_newlines(argv[i]));
2851 p += snprintf(p, 4096 - (p - buf), "'%s'", tmp);
2854 p += snprintf(p, 4096 - (p - buf), ");");
2855 if (p - buf > 4096)
2856 return 0;
2858 sm_msg("SQL: %s", buf);
2859 return 0;
2862 static void dump_cache(struct symbol_list *sym_list)
2864 const char *cache_tables[] = {
2865 "type_info", "return_implies", "call_implies", "mtag_data",
2866 "mtag_info", "mtag_about", "sink_info", "hash_string",
2868 char buf[64];
2869 int i;
2871 if (!option_info)
2872 return;
2874 for (i = 0; i < ARRAY_SIZE(cache_tables); i++) {
2875 snprintf(buf, sizeof(buf), "select * from %s;", cache_tables[i]);
2876 cache_sql(&save_cache_data, (char *)cache_tables[i], buf);
2880 void open_smatch_db(char *db_file)
2882 int rc;
2884 if (option_no_db)
2885 return;
2887 use_states = malloc(num_checks);
2888 memset(use_states, 0xff, num_checks);
2890 init_memdb();
2891 init_cachedb();
2893 rc = sqlite3_open_v2(db_file, &smatch_db, SQLITE_OPEN_READONLY, NULL);
2894 if (rc != SQLITE_OK) {
2895 option_no_db = 1;
2896 return;
2898 run_sql(NULL, NULL,
2899 "PRAGMA cache_size = %d;", SQLITE_CACHE_PAGES);
2900 return;
2903 static char *get_next_string(char **str)
2905 static char string[256];
2906 char *start;
2907 char *p = *str;
2908 int len, i, j;
2910 if (*p == '\0')
2911 return NULL;
2912 start = p;
2914 while (*p != '\0' && *p != '\n') {
2915 if (*p == '\\' && *(p + 1) == ' ') {
2916 p += 2;
2917 continue;
2919 if (*p == ' ')
2920 break;
2921 p++;
2924 len = p - start;
2925 if (len >= sizeof(string)) {
2926 memcpy(string, start, sizeof(string));
2927 string[sizeof(string) - 1] = '\0';
2928 sm_ierror("return_fix: '%s' too long", string);
2929 **str = '\0';
2930 return NULL;
2932 memcpy(string, start, len);
2933 string[len] = '\0';
2934 for (i = 0; i < sizeof(string) - 1; i++) {
2935 if (string[i] == '\\' && string[i + 1] == ' ') {
2936 for (j = i; string[j] != '\0'; j++)
2937 string[j] = string[j + 1];
2940 if (*p != '\0')
2941 p++;
2942 *str = p;
2943 return string;
2946 static void register_return_deletes(void)
2948 char *func, *ret_str;
2949 char filename[256];
2950 char buf[4096];
2951 int fd, ret, i;
2952 char *p;
2954 snprintf(filename, 256, "db/%s.delete.return_states", option_project_str);
2955 fd = open_schema_file(filename);
2956 if (fd < 0)
2957 return;
2958 ret = read(fd, buf, sizeof(buf));
2959 close(fd);
2960 if (ret < 0)
2961 return;
2962 if (ret == sizeof(buf)) {
2963 sm_ierror("file too large: %s (limit %zd bytes)",
2964 filename, sizeof(buf));
2965 return;
2967 buf[ret] = '\0';
2969 p = buf;
2970 while (*p) {
2971 get_next_string(&p);
2972 delete_count++;
2974 if (delete_count == 0)
2975 return;
2976 if (delete_count % 2 != 0) {
2977 printf("error parsing '%s' delete_count=%d\n", filename, delete_count);
2978 delete_count = 0;
2979 return;
2981 delete_table = malloc(delete_count * sizeof(char *));
2983 p = buf;
2984 i = 0;
2985 while (*p) {
2986 func = alloc_string(get_next_string(&p));
2987 ret_str = alloc_string(get_next_string(&p));
2989 delete_table[i++] = func;
2990 delete_table[i++] = ret_str;
2994 #define RETURN_FIX_SIZE 8196
2995 static void register_return_replacements(void)
2997 char *func, *orig, *new;
2998 char filename[256];
2999 int fd, ret, i;
3000 char *buf;
3001 char *p;
3003 snprintf(filename, 256, "db/%s.return_fixes", option_project_str);
3004 fd = open_schema_file(filename);
3005 if (fd < 0)
3006 return;
3007 buf = malloc(RETURN_FIX_SIZE);
3008 ret = read(fd, buf, RETURN_FIX_SIZE);
3009 close(fd);
3010 if (ret < 0) {
3011 free(buf);
3012 return;
3014 if (ret == RETURN_FIX_SIZE) {
3015 sm_ierror("file too large: %s (limit %d bytes)",
3016 filename, RETURN_FIX_SIZE);
3017 free(buf);
3018 return;
3020 buf[ret] = '\0';
3022 p = buf;
3023 while (*p) {
3024 get_next_string(&p);
3025 replace_count++;
3027 if (replace_count == 0) {
3028 free(buf);
3029 return;
3031 if (replace_count % 3 != 0) {
3032 printf("error parsing '%s' replace_count=%d\n", filename, replace_count);
3033 replace_count = 0;
3034 free(buf);
3035 return;
3037 replace_table = malloc(replace_count * sizeof(char *));
3039 p = buf;
3040 i = 0;
3041 while (*p) {
3042 func = alloc_string(get_next_string(&p));
3043 orig = alloc_string(get_next_string(&p));
3044 new = alloc_string(get_next_string(&p));
3046 replace_table[i++] = func;
3047 replace_table[i++] = orig;
3048 replace_table[i++] = new;
3050 free(buf);
3053 static void register_forced_return_splits(void)
3055 int struct_members = sizeof(struct split_data) / sizeof(char *);
3056 char filename[256];
3057 char buf[4096];
3058 int fd, ret, i;
3059 char *p;
3061 snprintf(filename, 256, "db/%s.forced_return_splits", option_project_str);
3062 fd = open_schema_file(filename);
3063 if (fd < 0)
3064 return;
3065 ret = read(fd, buf, sizeof(buf));
3066 close(fd);
3067 if (ret < 0)
3068 return;
3069 if (ret == sizeof(buf)) {
3070 sm_ierror("file too large: %s (limit %zd bytes)",
3071 filename, sizeof(buf));
3072 return;
3074 buf[ret] = '\0';
3076 p = buf;
3077 while (*p) {
3078 get_next_string(&p);
3079 split_count++;
3081 if (split_count == 0)
3082 return;
3083 if (split_count % struct_members != 0) {
3084 printf("error parsing '%s' split_count=%d\n", filename, split_count);
3085 split_count = 0;
3086 return;
3088 split_count /= struct_members;
3089 forced_splits = malloc(split_count * sizeof(void *));
3091 p = buf;
3092 i = 0;
3093 while (*p) {
3094 struct split_data *split = malloc(sizeof(*split));
3096 split->func = alloc_string(get_next_string(&p));
3097 split->rl = alloc_string(get_next_string(&p));
3098 forced_splits[i++] = split;
3102 void register_definition_db_callbacks(int id)
3104 my_id = id;
3106 add_hook(&match_call_info, FUNCTION_CALL_HOOK_BEFORE);
3107 add_hook(&match_call_info_new, FUNCTION_CALL_HOOK_BEFORE);
3108 add_split_return_callback(match_return_info);
3109 add_split_return_callback(print_returned_struct_members);
3110 add_split_return_callback(print_return_info);
3111 add_hook(&call_return_state_hooks, RETURN_HOOK);
3112 add_hook(&match_end_func_info, END_FUNC_HOOK);
3113 add_hook(&match_after_func, AFTER_FUNC_HOOK);
3115 add_hook(&match_data_from_db, FUNC_DEF_HOOK);
3116 add_hook(&match_call_implies, FUNC_DEF_HOOK);
3117 add_hook(&match_return_implies_early, CALL_HOOK_AFTER_INLINE);
3119 common_funcs = load_strings_from_file(option_project_str, "common_functions");
3120 register_return_deletes();
3121 register_return_replacements();
3122 register_forced_return_splits();
3124 add_hook(&dump_cache, END_FILE_HOOK);
3127 void register_definition_db_callbacks_late(int id)
3129 add_hook(&match_return_implies_late, CALL_HOOK_AFTER_INLINE);
3132 void register_db_call_marker(int id)
3134 add_hook(&match_call_marker, FUNCTION_CALL_HOOK_BEFORE);
3137 char *get_data_info_name(struct expression *expr)
3139 struct symbol *sym;
3140 char *name;
3141 char buf[256];
3142 char *ret = NULL;
3144 expr = strip_expr(expr);
3145 name = get_member_name(expr);
3146 if (name)
3147 return name;
3148 name = expr_to_var_sym(expr, &sym);
3149 if (!name || !sym)
3150 goto free;
3151 if (!(sym->ctype.modifiers & MOD_TOPLEVEL))
3152 goto free;
3153 if (sym->ctype.modifiers & MOD_STATIC)
3154 snprintf(buf, sizeof(buf), "static %s", name);
3155 else
3156 snprintf(buf, sizeof(buf), "global %s", name);
3157 ret = alloc_sname(buf);
3158 free:
3159 free_string(name);
3160 return ret;