unreachable: ignore all for_XXX macros
[smatch.git] / smatch_db.c
blob2064f88b5de26f0330a7fcea529080058352f395
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 sql_insert_or_ignore(return_implies, "0x%llx, '%s', %lu, %d, %d, %d, '%s', '%s'",
381 get_base_file_id(), get_function(), (unsigned long)__inline_fn,
382 fn_static(), type, param, key, value);
385 void sql_insert_call_implies(int type, int param, const char *key, const char *value)
387 sql_insert_or_ignore(call_implies, "0x%llx, '%s', %lu, %d, %d, %d, '%s', '%s'",
388 get_base_file_id(), get_function(), (unsigned long)__inline_fn,
389 fn_static(), type, param, key, value);
392 void sql_insert_function_type_size(const char *member, const char *ranges)
394 sql_insert(function_type_size, "0x%llx, '%s', '%s', '%s'", get_base_file_id(), get_function(), member, ranges);
397 void sql_insert_function_type_info(int type, const char *struct_type, const char *member, const char *value)
399 sql_insert(function_type_info, "0x%llx, '%s', %d, '%s', '%s', '%s'", get_base_file_id(), get_function(), type, struct_type, member, value);
402 void sql_insert_type_info(int type, const char *member, const char *value)
404 sql_insert_cache(type_info, "0x%llx, %d, '%s', '%s'", get_base_file_id(), type, member, value);
407 void sql_insert_local_values(const char *name, const char *value)
409 sql_insert(local_values, "0x%llx, '%s', '%s'", get_base_file_id(), name, value);
412 void sql_insert_function_type_value(const char *type, const char *value)
414 sql_insert(function_type_value, "0x%llx, '%s', '%s', '%s'", get_base_file_id(), get_function(), type, value);
417 void sql_insert_function_type(int param, const char *value)
419 sql_insert(function_type, "0x%llx, '%s', %d, %d, '%s'",
420 get_base_file_id(), get_function(), fn_static(), param, value);
423 void sql_insert_parameter_name(int param, const char *value)
425 sql_insert(parameter_name, "0x%llx, '%s', %d, %d, '%s'",
426 get_base_file_id(), get_function(), fn_static(), param, value);
429 void sql_insert_data_info(struct expression *data, int type, const char *value)
431 char *data_name;
433 data_name = get_data_info_name(data);
434 if (!data_name)
435 return;
436 sql_insert(data_info, "0x%llx, '%s', %d, '%s'",
437 is_static(data) ? get_base_file_id() : 0,
438 data_name, type, value);
441 void sql_insert_data_info_var_sym(const char *var, struct symbol *sym, int type, const char *value)
443 sql_insert(data_info, "0x%llx, '%s', %d, '%s'",
444 (sym->ctype.modifiers & MOD_STATIC) ? get_base_file_id() : 0,
445 var, type, value);
448 void sql_save_constraint(const char *con)
450 if (!option_info)
451 return;
453 sm_msg("SQL: insert or ignore into constraints (str) values('%s');", escape_newlines(con));
456 void sql_save_constraint_required(const char *data, int op, const char *limit)
458 sql_insert_or_ignore(constraints_required, "'%s', '%s', '%s'", data, show_special(op), limit);
461 void sql_copy_constraint_required(const char *new_limit, const char *old_limit)
463 if (!option_info)
464 return;
466 sm_msg("SQL_late: insert or ignore into constraints_required (data, op, bound) "
467 "select constraints_required.data, constraints_required.op, '%s' from "
468 "constraints_required where bound = '%s';", new_limit, old_limit);
471 void sql_insert_fn_ptr_data_link(const char *ptr, const char *data)
473 sql_insert_or_ignore(fn_ptr_data_link, "'%s', '%s'", ptr, data);
476 void sql_insert_fn_data_link(struct expression *fn, int type, int param, const char *key, const char *value)
478 if (fn->type != EXPR_SYMBOL || !fn->symbol->ident)
479 return;
481 sql_insert(fn_data_link, "0x%llx, '%s', %d, %d, %d, '%s', '%s'",
482 is_local(fn->symbol) ? get_base_file_id() : 0,
483 fn->symbol->ident->name,
484 is_local(fn->symbol),
485 type, param, key, value);
488 void sql_insert_mtag_about(mtag_t tag, const char *left_name, const char *right_name)
490 sql_insert_cache(mtag_about, "%lld, '%s', '%s', %d, '%s', '%s'",
491 tag, get_filename(), get_function(), get_lineno(),
492 left_name, right_name);
495 void sql_insert_mtag_info(mtag_t tag, int type, const char *value)
497 sql_insert_cache(mtag_info, "'%s', %lld, %d, '%s'", get_filename(), tag, type, value);
500 void sql_insert_mtag_map(mtag_t container, int container_offset, mtag_t tag, int tag_offset)
502 sql_insert(mtag_map, "%lld, %d, %lld, %d", container, container_offset, tag, tag_offset);
505 void sql_insert_mtag_alias(mtag_t orig, mtag_t alias)
507 sql_insert(mtag_alias, "%lld, %lld", orig, alias);
510 static int save_mtag(void *_tag, int argc, char **argv, char **azColName)
512 mtag_t *saved_tag = _tag;
513 mtag_t new_tag;
515 new_tag = strtoll(argv[0], NULL, 10);
517 if (!*saved_tag)
518 *saved_tag = new_tag;
519 else if (*saved_tag != new_tag)
520 *saved_tag = -1ULL;
522 return 0;
525 int mtag_map_select_container(mtag_t tag, int container_offset, mtag_t *container)
527 mtag_t tmp = 0;
529 run_sql(save_mtag, &tmp,
530 "select container from mtag_map where tag = %lld and container_offset = %d and tag_offset = 0;",
531 tag, container_offset);
533 if (tmp == 0 || tmp == -1ULL)
534 return 0;
535 *container = tmp;
536 return 1;
539 int mtag_map_select_tag(mtag_t container, int offset, mtag_t *tag)
541 mtag_t tmp = 0;
543 run_sql(save_mtag, &tmp,
544 "select tag from mtag_map where container = %lld and container_offset = %d;",
545 container, offset);
547 if (tmp == 0 || tmp == -1ULL)
548 return 0;
549 *tag = tmp;
550 return 1;
553 char *get_static_filter(struct symbol *sym)
555 static char sql_filter[1024];
557 /* This can only happen on buggy code. Return invalid SQL. */
558 if (!sym) {
559 sql_filter[0] = '\0';
560 return sql_filter;
563 if (is_local(sym)) {
564 snprintf(sql_filter, sizeof(sql_filter),
565 "file = 0x%llx and function = '%s' and static = '1'",
566 get_base_file_id(), sym->ident->name);
567 } else {
568 snprintf(sql_filter, sizeof(sql_filter),
569 "function = '%s' and static = '0'", sym->ident->name);
572 return sql_filter;
575 static int get_row_count(void *_row_count, int argc, char **argv, char **azColName)
577 int *row_count = _row_count;
579 *row_count = 0;
580 if (argc != 1)
581 return 0;
582 *row_count = atoi(argv[0]);
583 return 0;
586 static void mark_call_params_untracked(struct expression *call)
588 struct expression *arg;
589 int i = 0;
591 FOR_EACH_PTR(call->args, arg) {
592 mark_untracked(call, i++, "$", NULL);
593 } END_FOR_EACH_PTR(arg);
596 static void sql_select_return_states_pointer(const char *cols,
597 struct expression *call, int (*callback)(void*, int, char**, char**), void *info)
599 char *ptr;
600 int return_count = 0;
602 ptr = get_fnptr_name(call->fn);
603 if (!ptr)
604 return;
606 run_sql(get_row_count, &return_count,
607 "select count(*) from return_states join function_ptr "
608 "where return_states.function == function_ptr.function and "
609 "ptr = '%s' and searchable = 1 and type = %d;", ptr, INTERNAL);
610 /* The magic number 100 is just from testing on the kernel. */
611 if (return_count == 0 || return_count > 100) {
612 run_sql(callback, info,
613 "select distinct %s from return_states join function_ptr where "
614 "return_states.function == function_ptr.function and ptr = '%s' "
615 "and searchable = 1 and type = %d "
616 "order by function_ptr.file, return_states.file, return_id, type;",
617 cols, ptr, INTERNAL);
618 mark_call_params_untracked(call);
619 return;
622 run_sql(callback, info,
623 "select %s from return_states join function_ptr where "
624 "return_states.function == function_ptr.function and ptr = '%s' "
625 "and searchable = 1 "
626 "order by function_ptr.file, return_states.file, return_id, type;",
627 cols, ptr);
630 static int is_local_symbol(struct expression *expr)
632 if (expr->type != EXPR_SYMBOL)
633 return 0;
634 if (expr->symbol->ctype.modifiers & (MOD_NONLOCAL | MOD_STATIC | MOD_ADDRESSABLE))
635 return 0;
636 return 1;
639 bool is_fn_ptr(struct expression *fn)
641 fn = strip_expr(fn);
642 if (fn->type != EXPR_SYMBOL)
643 return true;
644 if (!fn->symbol)
645 return true;
646 if (is_local_symbol(fn))
647 return true;
648 return false;
651 void sql_select_return_states(const char *cols, struct expression *call,
652 int (*callback)(void*, int, char**, char**), void *info)
654 struct expression *fn;
655 int row_count = 0;
657 if (is_fake_call(call))
658 return;
660 fn = strip_expr(call->fn);
661 if (is_fn_ptr(fn)) {
662 sql_select_return_states_pointer(cols, call, callback, info);
663 return;
666 if (inlinable(fn)) {
667 mem_sql(callback, info,
668 "select %s from return_states where call_id = '%lu' order by return_id, type;",
669 cols, (unsigned long)call);
670 return;
673 run_sql(get_row_count, &row_count, "select count(*) from return_states where %s;",
674 get_static_filter(fn->symbol));
675 if (row_count == 0 && fn->symbol && fn->symbol->definition)
676 set_state(my_id, "db_incomplete", NULL, &incomplete);
677 if (row_count == 0 || row_count > 3000) {
678 mark_call_params_untracked(call);
679 return;
682 run_sql(callback, info, "select %s from return_states where %s order by file, return_id, type;",
683 cols, get_static_filter(fn->symbol));
686 bool db_incomplete(void)
688 return !!get_state(my_id, "db_incomplete", NULL);
691 #define CALL_IMPLIES 0
692 #define RETURN_IMPLIES 1
694 struct implies_info {
695 int type;
696 struct db_implies_cb_list *cb_list;
697 struct expression *expr;
698 struct symbol *sym;
701 void sql_select_implies(const char *cols, struct implies_info *info,
702 int (*callback)(void*, int, char**, char**))
704 if (info->type == RETURN_IMPLIES && inlinable(info->expr->fn)) {
705 mem_sql(callback, info,
706 "select %s from return_implies where call_id = '%lu';",
707 cols, (unsigned long)info->expr);
708 return;
711 run_sql(callback, info, "select %s from %s_implies where %s;",
712 cols,
713 info->type == CALL_IMPLIES ? "call" : "return",
714 get_static_filter(info->sym));
717 struct select_caller_info_data {
718 struct stree *final_states;
719 struct timeval start_time;
720 int prev_func_id;
721 int ignore;
722 int results;
725 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName);
727 static void sql_select_caller_info(struct select_caller_info_data *data,
728 const char *cols, struct symbol *sym)
730 if (__inline_fn) {
731 mem_sql(caller_info_callback, data,
732 "select %s from caller_info where call_id = %lu;",
733 cols, (unsigned long)__inline_fn);
734 return;
737 if (is_common_function(sym->ident->name))
738 return;
739 run_sql(caller_info_callback, data,
740 "select %s from common_caller_info where %s order by call_id;",
741 cols, get_static_filter(sym));
742 if (data->results)
743 return;
745 run_sql(caller_info_callback, data,
746 "select %s from caller_info where %s order by call_id;",
747 cols, get_static_filter(sym));
750 void select_caller_info_hook(void (*callback)(const char *name, struct symbol *sym, char *key, char *value), int type)
752 struct def_callback *def_callback = __alloc_def_callback(0);
754 def_callback->hook_type = type;
755 def_callback->callback = callback;
756 add_ptr_list(&select_caller_info_callbacks, def_callback);
759 void select_caller_name_sym(void (*fn)(const char *name, struct symbol *sym, char *value), int type)
761 struct def_name_sym_callback *callback = __alloc_def_name_sym_callback(0);
763 callback->hook_type = type;
764 callback->callback = fn;
765 add_ptr_list(&select_caller_name_sym_callbacks, callback);
769 * These call backs are used when the --info option is turned on to print struct
770 * member information. For example foo->bar could have a state in
771 * smatch_extra.c and also check_user.c.
773 void add_member_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
775 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
777 member_callback->owner = owner;
778 member_callback->callback = callback;
779 add_ptr_list(&member_callbacks, member_callback);
782 void add_caller_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
784 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
786 member_callback->owner = owner;
787 member_callback->callback = callback;
788 add_ptr_list(&member_callbacks_new, member_callback);
791 void add_return_info_callback(int owner,
792 void (*callback)(int return_id, char *return_ranges,
793 struct expression *returned_expr,
794 int param,
795 const char *printed_name,
796 struct sm_state *sm))
798 struct return_info_callback *return_callback = __alloc_return_info_callback(0);
800 return_callback->owner = owner;
801 return_callback->callback = callback;
802 add_ptr_list(&return_callbacks, return_callback);
805 void add_split_return_callback(void (*fn)(int return_id, char *return_ranges, struct expression *returned_expr))
807 struct returned_state_callback *callback = __alloc_returned_state_callback(0);
809 callback->callback = fn;
810 add_ptr_list(&returned_state_callbacks, callback);
813 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))
815 struct returned_member_callback *member_callback = __alloc_returned_member_callback(0);
817 member_callback->owner = owner;
818 member_callback->callback = callback;
819 add_ptr_list(&returned_member_callbacks, member_callback);
822 void select_call_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
824 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
826 cb->type = type;
827 cb->callback = callback;
828 add_ptr_list(&call_implies_cb_list, cb);
831 void select_return_implies_hook_early(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
833 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
835 cb->type = type;
836 cb->callback = callback;
837 add_ptr_list(&return_implies_cb_list_early, cb);
840 void select_return_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
842 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
844 cb->type = type;
845 cb->callback = callback;
846 add_ptr_list(&return_implies_cb_list_late, cb);
849 struct return_info {
850 struct expression *static_returns_call;
851 struct symbol *return_type;
852 struct range_list *return_range_list;
855 static int db_return_callback(void *_ret_info, int argc, char **argv, char **azColName)
857 struct return_info *ret_info = _ret_info;
858 struct range_list *rl;
859 struct expression *call_expr = ret_info->static_returns_call;
861 if (argc != 1)
862 return 0;
863 call_results_to_rl(call_expr, ret_info->return_type, argv[0], &rl);
864 ret_info->return_range_list = rl_union(ret_info->return_range_list, rl);
865 return 0;
868 static struct expression *cached_expr, *cached_no_args;
869 static const char *cached_str;
870 static struct range_list *cached_rl, *cached_str_rl, *cached_no_args_rl;
872 static void clear_cached_return_vals(void)
874 cached_expr = NULL;
875 cached_rl = NULL;
876 cached_str = NULL;
877 cached_str_rl = NULL;
878 cached_no_args = NULL;
879 cached_no_args_rl = NULL;
882 struct range_list *db_return_vals(struct expression *expr)
884 struct return_info ret_info = {};
885 struct sm_state *sm;
887 if (!expr)
888 return NULL;
890 if (is_fake_call(expr))
891 return NULL;
893 if (expr == cached_expr)
894 return clone_rl(cached_rl);
896 cached_expr = expr;
897 cached_rl = NULL;
899 sm = get_extra_sm_state(expr);
900 if (sm) {
901 cached_rl = clone_rl(estate_rl(sm->state));
902 return clone_rl(estate_rl(sm->state));
904 ret_info.static_returns_call = expr;
905 ret_info.return_type = get_type(expr);
906 if (!ret_info.return_type)
907 return NULL;
909 if (expr->fn->type != EXPR_SYMBOL || !expr->fn->symbol)
910 return NULL;
912 ret_info.return_range_list = NULL;
913 if (inlinable(expr->fn)) {
914 mem_sql(db_return_callback, &ret_info,
915 "select distinct return from return_states where call_id = '%lu';",
916 (unsigned long)expr);
917 } else {
918 run_sql(db_return_callback, &ret_info,
919 "select distinct return from return_states where %s;",
920 get_static_filter(expr->fn->symbol));
922 cached_rl = clone_rl(ret_info.return_range_list);
923 return ret_info.return_range_list;
926 struct range_list *db_return_vals_from_str(const char *fn_name)
928 struct return_info ret_info;
930 if (!fn_name)
931 return NULL;
932 if (fn_name == cached_str)
933 return clone_rl(cached_str_rl);
934 cached_str = fn_name;
935 cached_str_rl = NULL;
937 ret_info.static_returns_call = NULL;
938 ret_info.return_type = &llong_ctype;
939 ret_info.return_range_list = NULL;
941 run_sql(db_return_callback, &ret_info,
942 "select distinct return from return_states where function = '%s';",
943 fn_name);
944 cached_str_rl = clone_rl(ret_info.return_range_list);
945 return ret_info.return_range_list;
949 * This is used when we have a function that takes a function pointer as a
950 * parameter. "frob(blah, blah, my_function);" We know that the return values
951 * from frob() come from my_funcion() so we want to find the possible returns
952 * of my_function(), but we don't know which arguments are passed to it.
955 struct range_list *db_return_vals_no_args(struct expression *expr)
957 struct return_info ret_info = {};
959 if (!expr || expr->type != EXPR_SYMBOL)
960 return NULL;
962 if (expr == cached_no_args)
963 return clone_rl(cached_no_args_rl);
964 cached_no_args = expr;
965 cached_no_args_rl = NULL;
967 ret_info.static_returns_call = expr;
968 ret_info.return_type = get_type(expr);
969 ret_info.return_type = get_real_base_type(ret_info.return_type);
970 if (!ret_info.return_type)
971 return NULL;
973 run_sql(db_return_callback, &ret_info,
974 "select distinct return from return_states where %s;",
975 get_static_filter(expr->symbol));
977 cached_no_args_rl = clone_rl(ret_info.return_range_list);
978 return ret_info.return_range_list;
981 static void match_call_marker(struct expression *expr)
983 struct symbol *type;
985 type = get_type(expr->fn);
986 if (type && type->type == SYM_PTR)
987 type = get_real_base_type(type);
990 * we just want to record something in the database so that if we have
991 * two calls like: frob(4); frob(some_unkown); then on the receiving
992 * side we know that sometimes frob is called with unknown parameters.
995 sql_insert_caller_info(expr, INTERNAL, -1, "%call_marker%", type_to_str(type));
998 int is_recursive_member(const char *name)
1000 char buf[256];
1001 const char *p, *next;
1002 int size;
1004 p = strchr(name, '>');
1005 if (!p)
1006 return 0;
1007 p++;
1008 while (true) {
1009 next = strchr(p, '>');
1010 if (!next)
1011 return 0;
1012 next++;
1014 size = next - p;
1015 if (size >= sizeof(buf))
1016 return 0;
1017 memcpy(buf, p, size);
1018 buf[size] = '\0';
1019 if (strstr(next, buf))
1020 return 1;
1021 p = next;
1025 char *sm_to_arg_name(struct expression *expr, struct sm_state *sm)
1027 struct symbol *sym;
1028 const char *sm_name;
1029 char *name;
1030 bool is_address = false;
1031 bool add_star = false;
1032 char buf[256];
1033 char *ret = NULL;
1034 int len;
1036 expr = strip_expr(expr);
1037 if (!expr)
1038 return NULL;
1040 if (expr->type == EXPR_PREOP && expr->op == '&') {
1041 expr = strip_expr(expr->unop);
1042 is_address = true;
1045 name = expr_to_var_sym(expr, &sym);
1046 if (!name || !sym)
1047 goto free;
1048 if (sym != sm->sym)
1049 goto free;
1051 sm_name = sm->name;
1052 add_star = false;
1053 if (sm_name[0] == '*') {
1054 add_star = true;
1055 sm_name++;
1058 len = strlen(name);
1059 if (strncmp(name, sm_name, len) != 0)
1060 goto free;
1061 if (sm_name[len] == '\0') {
1062 snprintf(buf, sizeof(buf), "%s%s$",
1063 add_star ? "*" : "", is_address ? "*" : "");
1064 } else {
1065 if (sm_name[len] != '.' && sm_name[len] != '-')
1066 goto free;
1067 if (sm_name[len] == '-')
1068 len++;
1069 // FIXME does is_address really imply that sm_name[len] == '-'
1070 snprintf(buf, sizeof(buf), "%s$->%s", add_star ? "*" : "",
1071 sm_name + len);
1074 ret = alloc_sname(buf);
1075 free:
1076 free_string(name);
1077 return ret;
1080 static void print_struct_members(struct expression *call, struct expression *expr, int param,
1081 int owner,
1082 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm),
1083 bool new)
1085 struct sm_state *sm;
1086 const char *sm_name;
1087 char *name;
1088 struct symbol *sym;
1089 int len;
1090 char printed_name[256];
1091 int is_address = 0;
1092 bool add_star;
1093 struct symbol *type;
1095 expr = strip_expr(expr);
1096 if (!expr)
1097 return;
1098 type = get_type(expr);
1099 if (!new && type && type_bits(type) < type_bits(&ulong_ctype))
1100 return;
1102 if (expr->type == EXPR_PREOP && expr->op == '&') {
1103 expr = strip_expr(expr->unop);
1104 is_address = 1;
1107 name = expr_to_var_sym(expr, &sym);
1108 if (!name || !sym)
1109 goto free;
1111 len = strlen(name);
1112 FOR_EACH_SM(__get_cur_stree(), sm) {
1113 if (sm->owner != owner || sm->sym != sym)
1114 continue;
1116 sm_name = sm->name;
1117 add_star = false;
1118 if (sm_name[0] == '*') {
1119 add_star = true;
1120 sm_name++;
1122 // FIXME: simplify?
1123 if (!add_star && strcmp(name, sm_name) == 0) {
1124 if (is_address) {
1125 snprintf(printed_name, sizeof(printed_name), "*$");
1126 } else {
1127 if (new)
1128 snprintf(printed_name, sizeof(printed_name), "$");
1129 else
1130 continue;
1132 } else if (add_star && strcmp(name, sm_name) == 0) {
1133 snprintf(printed_name, sizeof(printed_name), "%s*$",
1134 is_address ? "*" : "");
1135 } else if (strncmp(name, sm_name, len) == 0) {
1136 if (sm_name[len] != '.' && sm_name[len] != '-')
1137 continue;
1138 if (is_address && sm_name[len] == '.') {
1139 snprintf(printed_name, sizeof(printed_name),
1140 "%s$->%s", add_star ? "*" : "",
1141 sm_name + len + 1);
1142 } else if (is_address && sm_name[len] == '-') {
1143 snprintf(printed_name, sizeof(printed_name),
1144 "%s(*$)%s", add_star ? "*" : "",
1145 sm_name + len);
1146 } else {
1147 snprintf(printed_name, sizeof(printed_name),
1148 "%s$%s", add_star ? "*" : "",
1149 sm_name + len);
1151 } else if (sm_name[0] == '&' && strncmp(name, sm_name + 1, len) == 0) {
1152 if (sm_name[len + 1] != '.' && sm_name[len + 1] != '-')
1153 continue;
1154 if (is_address && sm_name[len + 1] == '.') {
1155 snprintf(printed_name, sizeof(printed_name),
1156 "&%s$->%s", add_star ? "*" : "",
1157 sm_name + len + 2);
1158 } else if (is_address && sm_name[len] == '-') {
1159 snprintf(printed_name, sizeof(printed_name),
1160 "&%s(*$)%s", add_star ? "*" : "",
1161 sm_name + len + 1);
1162 } else {
1163 snprintf(printed_name, sizeof(printed_name),
1164 "&%s$%s", add_star ? "*" : "",
1165 sm_name + len + 1);
1167 } else {
1168 continue;
1170 if (is_recursive_member(printed_name))
1171 continue;
1172 callback(call, param, printed_name, sm);
1173 } END_FOR_EACH_SM(sm);
1174 free:
1175 free_string(name);
1178 static void match_call_info(struct expression *call)
1180 struct member_info_callback *cb;
1181 struct expression *arg;
1182 int i;
1184 FOR_EACH_PTR(member_callbacks, cb) {
1185 i = -1;
1186 FOR_EACH_PTR(call->args, arg) {
1187 i++;
1188 print_struct_members(call, arg, i, cb->owner, cb->callback, 0);
1189 } END_FOR_EACH_PTR(arg);
1190 } END_FOR_EACH_PTR(cb);
1193 static struct expression *get_fake_variable(struct expression *expr)
1195 struct expression *tmp;
1197 tmp = expr_get_fake_parent_expr(expr);
1198 if (!tmp || tmp->type != EXPR_ASSIGNMENT)
1199 return NULL;
1201 return tmp->left;
1204 static struct sm_state *get_returned_sm(struct expression *expr)
1206 struct expression *fake;
1208 fake = get_fake_variable(expr);
1209 if (fake)
1210 expr = fake;
1212 return get_sm_state_expr(SMATCH_EXTRA, expr);
1215 static void match_call_info_new(struct expression *call)
1217 struct member_info_callback *cb;
1218 struct expression *arg, *tmp;
1219 int i;
1221 if (!option_info && !__inline_call && !local_debug)
1222 return;
1224 FOR_EACH_PTR(member_callbacks_new, cb) {
1225 i = -1;
1226 FOR_EACH_PTR(call->args, arg) {
1227 i++;
1228 tmp = get_fake_variable(arg);
1229 if (!tmp)
1230 tmp = arg;
1231 __ignore_param_used++;
1232 print_struct_members(call, tmp, i, cb->owner, cb->callback, 1);
1233 __ignore_param_used--;
1234 } END_FOR_EACH_PTR(arg);
1235 } END_FOR_EACH_PTR(cb);
1238 static int get_param(int param, char **name, struct symbol **sym)
1240 struct symbol *arg;
1241 int i;
1243 i = 0;
1244 FOR_EACH_PTR(cur_func_sym->ctype.base_type->arguments, arg) {
1245 if (i == param) {
1246 *name = arg->ident->name;
1247 *sym = arg;
1248 return TRUE;
1250 i++;
1251 } END_FOR_EACH_PTR(arg);
1253 return FALSE;
1256 static int function_signature_matches(const char *sig)
1258 char *my_sig;
1260 my_sig = function_signature();
1261 if (!sig || !my_sig)
1262 return 1; /* default to matching */
1263 if (strcmp(my_sig, sig) == 0)
1264 return 1;
1265 return 0;
1268 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName)
1270 struct select_caller_info_data *data = _data;
1271 int func_id;
1272 long type;
1273 long param;
1274 char *key;
1275 char *value;
1276 char *name = NULL;
1277 struct symbol *sym = NULL;
1278 struct def_callback *def_callback;
1279 struct def_name_sym_callback *ns_callback;
1280 struct stree *stree;
1281 struct timeval cur_time;
1282 char fullname[256];
1283 char *p;
1285 data->results = 1;
1287 if (argc != 5)
1288 return 0;
1290 gettimeofday(&cur_time, NULL);
1291 if (cur_time.tv_sec - data->start_time.tv_sec > 10)
1292 return 0;
1294 func_id = atoi(argv[0]);
1295 errno = 0;
1296 type = strtol(argv[1], NULL, 10);
1297 param = strtol(argv[2], NULL, 10);
1298 if (errno)
1299 return 0;
1300 key = argv[3];
1301 value = argv[4];
1303 if (data->prev_func_id == -1)
1304 data->prev_func_id = func_id;
1305 if (func_id != data->prev_func_id) {
1306 stree = __pop_fake_cur_stree();
1307 if (!data->ignore)
1308 merge_stree(&data->final_states, stree);
1309 free_stree(&stree);
1310 __push_fake_cur_stree();
1311 __unnullify_path();
1312 data->prev_func_id = func_id;
1313 data->ignore = 0;
1316 if (data->ignore)
1317 return 0;
1318 if (type == INTERNAL &&
1319 !function_signature_matches(value)) {
1320 data->ignore = 1;
1321 return 0;
1324 if (param >= 0 && !get_param(param, &name, &sym))
1325 return 0;
1327 FOR_EACH_PTR(select_caller_info_callbacks, def_callback) {
1328 if (def_callback->hook_type == type)
1329 def_callback->callback(name, sym, key, value);
1330 } END_FOR_EACH_PTR(def_callback);
1332 p = strchr(key, '$');
1333 if (name && p)
1334 snprintf(fullname, sizeof(fullname), "%.*s%s%s", (int)(p - key), key, name, p + 1);
1335 else
1336 snprintf(fullname, sizeof(fullname), "%s", key);
1338 FOR_EACH_PTR(select_caller_name_sym_callbacks, ns_callback) {
1339 if (ns_callback->hook_type == type)
1340 ns_callback->callback(fullname, sym, value);
1341 } END_FOR_EACH_PTR(ns_callback);
1343 return 0;
1346 static struct string_list *ptr_names_done;
1347 static struct string_list *ptr_names;
1349 static int get_ptr_name(void *unused, int argc, char **argv, char **azColName)
1351 insert_string(&ptr_names, alloc_string(argv[0]));
1352 return 0;
1355 static char *get_next_ptr_name(void)
1357 char *ptr;
1359 FOR_EACH_PTR(ptr_names, ptr) {
1360 if (!insert_string(&ptr_names_done, ptr))
1361 continue;
1362 return ptr;
1363 } END_FOR_EACH_PTR(ptr);
1364 return NULL;
1367 static void get_ptr_names(unsigned long long file, const char *name)
1369 char sql_filter[1024];
1370 int before, after;
1372 if (file) {
1373 snprintf(sql_filter, 1024, "file = 0x%llx and function = '%s';",
1374 file, name);
1375 } else {
1376 snprintf(sql_filter, 1024, "function = '%s';", name);
1379 before = ptr_list_size((struct ptr_list *)ptr_names);
1381 run_sql(get_ptr_name, NULL,
1382 "select distinct ptr from function_ptr where %s",
1383 sql_filter);
1385 after = ptr_list_size((struct ptr_list *)ptr_names);
1386 if (before == after)
1387 return;
1389 while ((name = get_next_ptr_name()))
1390 get_ptr_names(0, name);
1393 static void match_data_from_db(struct symbol *sym)
1395 struct select_caller_info_data data = { .prev_func_id = -1 };
1396 struct sm_state *sm;
1397 struct stree *stree;
1398 struct timeval end_time;
1400 if (!sym || !sym->ident)
1401 return;
1403 set_fn_mtag(sym);
1404 gettimeofday(&data.start_time, NULL);
1406 __push_fake_cur_stree();
1407 __unnullify_path();
1409 if (!__inline_fn) {
1410 char *ptr;
1412 if (sym->ctype.modifiers & MOD_STATIC)
1413 get_ptr_names(get_base_file_id(), sym->ident->name);
1414 else
1415 get_ptr_names(0, sym->ident->name);
1417 if (ptr_list_size((struct ptr_list *)ptr_names) > 20) {
1418 __free_ptr_list((struct ptr_list **)&ptr_names);
1419 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1420 __free_fake_cur_stree();
1421 return;
1424 sql_select_caller_info(&data,
1425 "call_id, type, parameter, key, value",
1426 sym);
1429 stree = __pop_fake_cur_stree();
1430 if (!data.ignore)
1431 merge_stree(&data.final_states, stree);
1432 free_stree(&stree);
1433 __push_fake_cur_stree();
1434 __unnullify_path();
1435 data.prev_func_id = -1;
1436 data.ignore = 0;
1437 data.results = 0;
1439 FOR_EACH_PTR(ptr_names, ptr) {
1440 run_sql(caller_info_callback, &data,
1441 "select call_id, type, parameter, key, value"
1442 " from common_caller_info where function = '%s' order by call_id",
1443 ptr);
1444 } END_FOR_EACH_PTR(ptr);
1446 if (data.results) {
1447 FOR_EACH_PTR(ptr_names, ptr) {
1448 free_string(ptr);
1449 } END_FOR_EACH_PTR(ptr);
1450 goto free_ptr_names;
1453 FOR_EACH_PTR(ptr_names, ptr) {
1454 run_sql(caller_info_callback, &data,
1455 "select call_id, type, parameter, key, value"
1456 " from caller_info where function = '%s' order by call_id",
1457 ptr);
1458 free_string(ptr);
1459 } END_FOR_EACH_PTR(ptr);
1461 free_ptr_names:
1462 __free_ptr_list((struct ptr_list **)&ptr_names);
1463 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1464 } else {
1465 sql_select_caller_info(&data,
1466 "call_id, type, parameter, key, value",
1467 sym);
1470 stree = __pop_fake_cur_stree();
1471 if (!data.ignore)
1472 merge_stree(&data.final_states, stree);
1473 free_stree(&stree);
1475 gettimeofday(&end_time, NULL);
1476 if (end_time.tv_sec - data.start_time.tv_sec <= 10) {
1477 FOR_EACH_SM(data.final_states, sm) {
1478 __set_sm(sm);
1479 } END_FOR_EACH_SM(sm);
1482 free_stree(&data.final_states);
1485 static int return_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1487 struct implies_info *info = _info;
1488 struct db_implies_callback *cb;
1489 struct expression *arg = NULL;
1490 int type;
1491 int param;
1493 if (argc != 5)
1494 return 0;
1496 type = atoi(argv[1]);
1497 param = atoi(argv[2]);
1499 FOR_EACH_PTR(info->cb_list, cb) {
1500 if (cb->type != type)
1501 continue;
1502 if (param != -1) {
1503 arg = get_argument_from_call_expr(info->expr->args, param);
1504 if (!arg)
1505 continue;
1507 cb->callback(info->expr, arg, argv[3], argv[4]);
1508 } END_FOR_EACH_PTR(cb);
1510 return 0;
1513 static int call_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1515 struct implies_info *info = _info;
1516 struct db_implies_callback *cb;
1517 struct expression *arg;
1518 struct symbol *sym;
1519 char *name;
1520 int type;
1521 int param;
1523 if (argc != 5)
1524 return 0;
1526 type = atoi(argv[1]);
1527 param = atoi(argv[2]);
1529 if (!get_param(param, &name, &sym))
1530 return 0;
1531 arg = symbol_expression(sym);
1532 if (!arg)
1533 return 0;
1535 FOR_EACH_PTR(info->cb_list, cb) {
1536 if (cb->type != type)
1537 continue;
1538 cb->callback(info->expr, arg, argv[3], argv[4]);
1539 } END_FOR_EACH_PTR(cb);
1541 return 0;
1544 static void match_return_implies_helper(struct expression *expr, struct db_implies_cb_list *cb_list)
1546 struct implies_info info = {
1547 .type = RETURN_IMPLIES,
1548 .cb_list = cb_list,
1551 if (expr->fn->type != EXPR_SYMBOL ||
1552 !expr->fn->symbol)
1553 return;
1554 info.expr = expr;
1555 info.sym = expr->fn->symbol;
1556 sql_select_implies("function, type, parameter, key, value", &info,
1557 return_implies_callbacks);
1560 static void match_return_implies_early(struct expression *expr)
1562 match_return_implies_helper(expr, return_implies_cb_list_early);
1565 static void match_return_implies_late(struct expression *expr)
1567 match_return_implies_helper(expr, return_implies_cb_list_late);
1570 static void match_call_implies(struct symbol *sym)
1572 struct implies_info info = {
1573 .type = CALL_IMPLIES,
1574 .cb_list = call_implies_cb_list,
1577 if (!sym || !sym->ident)
1578 return;
1580 info.sym = sym;
1581 sql_select_implies("function, type, parameter, key, value", &info,
1582 call_implies_callbacks);
1585 static char *get_fn_param_str(struct expression *expr)
1587 struct expression *tmp;
1588 int param;
1589 char buf[32];
1591 tmp = get_assigned_expr(expr);
1592 if (tmp)
1593 expr = tmp;
1594 expr = strip_expr(expr);
1595 if (!expr || expr->type != EXPR_CALL)
1596 return NULL;
1597 expr = strip_expr(expr->fn);
1598 if (!expr || expr->type != EXPR_SYMBOL)
1599 return NULL;
1600 param = get_param_num(expr);
1601 if (param < 0)
1602 return NULL;
1604 snprintf(buf, sizeof(buf), "[r $%d]", param);
1605 return alloc_sname(buf);
1608 static char *get_return_compare_is_param(struct expression *expr)
1610 char *var;
1611 char buf[256];
1612 int comparison;
1613 int param;
1615 param = get_param_num(expr);
1616 if (param < 0)
1617 return NULL;
1619 var = expr_to_var(expr);
1620 if (!var)
1621 return NULL;
1622 snprintf(buf, sizeof(buf), "%s orig", var);
1623 comparison = get_comparison_strings(var, buf);
1624 free_string(var);
1626 if (!comparison)
1627 return NULL;
1629 snprintf(buf, sizeof(buf), "[%s$%d]", show_special(comparison), param);
1630 return alloc_sname(buf);
1633 static char *get_return_compare_str(struct expression *expr)
1635 char *compare_str;
1637 compare_str = get_return_compare_is_param(expr);
1638 if (compare_str)
1639 return compare_str;
1641 compare_str = expr_lte_to_param(expr, -1);
1642 if (compare_str)
1643 return compare_str;
1645 return expr_param_comparison(expr, -1);
1648 static const char *get_return_ranges_str(struct expression *expr, struct range_list **rl_p)
1650 struct expression *fake;
1651 struct range_list *rl;
1652 const char *return_ranges;
1653 sval_t sval;
1654 const char *container_of_str;
1655 const char *math_str;
1656 char *fn_param_str;
1657 char *compare_str;
1658 char buf[128];
1660 *rl_p = NULL;
1662 if (!expr)
1663 return alloc_sname("");
1665 fake = get_fake_variable(expr);
1666 if (fake)
1667 expr = fake;
1669 container_of_str = get_container_of_str(expr);
1671 if (get_implied_value(expr, &sval)) {
1672 sval = sval_cast(cur_func_return_type(), sval);
1673 *rl_p = alloc_rl(sval, sval);
1674 return_ranges = sval_to_str_or_err_ptr(sval);
1675 if (container_of_str) {
1676 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1677 return alloc_sname(buf);
1679 return return_ranges;
1682 fn_param_str = get_fn_param_str(expr);
1683 math_str = get_param_key_swap_dollar(expr);
1684 compare_str = expr_equal_to_param(expr, -1);
1685 if (!math_str)
1686 math_str = get_value_in_terms_of_parameter_math(expr);
1688 if (get_implied_rl(expr, &rl) && !is_whole_rl(rl)) {
1689 rl = cast_rl(cur_func_return_type(), rl);
1690 return_ranges = show_rl(rl);
1691 } else if (get_imaginary_absolute(expr, &rl)){
1692 rl = cast_rl(cur_func_return_type(), rl);
1693 return alloc_sname(show_rl(rl));
1694 } else {
1695 get_absolute_rl(expr, &rl);
1696 rl = cast_rl(cur_func_return_type(), rl);
1697 return_ranges = show_rl(rl);
1699 *rl_p = rl;
1701 if (container_of_str) {
1702 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, container_of_str);
1703 return alloc_sname(buf);
1705 if (fn_param_str) {
1706 snprintf(buf, sizeof(buf), "%s%s", return_ranges, fn_param_str);
1707 return alloc_sname(buf);
1709 if (compare_str) {
1710 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1711 return alloc_sname(buf);
1713 if (math_str) {
1714 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, math_str);
1715 return alloc_sname(buf);
1717 compare_str = get_return_compare_str(expr);
1718 if (compare_str) {
1719 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1720 return alloc_sname(buf);
1723 return return_ranges;
1726 static void match_return_info(int return_id, char *return_ranges, struct expression *expr)
1728 sql_insert_return_states(return_id, return_ranges, INTERNAL, -1, "", function_signature());
1731 static bool call_return_state_hooks_conditional(struct expression *expr)
1733 int final_pass_orig = final_pass;
1734 static int recurse;
1736 if (recurse >= 2)
1737 return false;
1738 if (!expr ||
1739 (expr->type != EXPR_CONDITIONAL && expr->type != EXPR_SELECT))
1740 return false;
1742 recurse++;
1744 __push_fake_cur_stree();
1746 final_pass = 0;
1747 __split_whole_condition(expr->conditional);
1748 final_pass = final_pass_orig;
1750 call_return_state_hooks(expr->cond_true ?: expr->conditional);
1752 __push_true_states();
1753 __use_false_states();
1755 call_return_state_hooks(expr->cond_false);
1757 __merge_true_states();
1758 __free_fake_cur_stree();
1760 recurse--;
1761 return true;
1764 static bool handle_forced_split(const char *return_ranges, struct expression *expr)
1766 struct split_data *data = NULL;
1767 struct expression *compare;
1768 struct range_list *rl;
1769 char buf[64];
1770 char *math;
1771 sval_t sval;
1772 bool undo;
1773 int i;
1775 for (i = 0; i < split_count; i++) {
1776 if (get_function() &&
1777 strcmp(get_function(), forced_splits[i]->func) == 0) {
1778 data = forced_splits[i];
1779 break;
1782 if (!data)
1783 return false;
1785 // FIXME: this works for copy_to/from_user() because the only thing we
1786 // care about is zero/non-zero
1787 if (strcmp(data->rl, "0") != 0)
1788 return false;
1790 compare = compare_expression(expr, SPECIAL_EQUAL, zero_expr());
1791 if (!compare)
1792 return false;
1793 if (get_implied_value(compare, &sval))
1794 return false;
1796 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
1797 call_return_states_callbacks("0", expr);
1798 if (undo)
1799 end_assume();
1801 undo = assume(compare_expression(expr, SPECIAL_NOTEQUAL, zero_expr()));
1802 if (get_implied_rl(expr, &rl)) {
1803 math = strchr(return_ranges, '[');
1804 snprintf(buf, sizeof(buf), "%s%s", show_rl(rl), math ?: "");
1805 } else {
1806 snprintf(buf, sizeof(buf), "%s", return_ranges);
1808 call_return_states_callbacks(buf, expr);
1809 if (undo)
1810 end_assume();
1812 return true;
1815 static void call_return_states_callbacks(const char *return_ranges, struct expression *expr)
1817 struct returned_state_callback *cb;
1819 return_ranges = replace_return_ranges(return_ranges);
1820 if (is_delete_return(return_ranges))
1821 return;
1822 if (is_project_delete_return(expr))
1823 return;
1824 if (handle_forced_split(return_ranges, expr))
1825 return;
1827 return_id++;
1828 FOR_EACH_PTR(returned_state_callbacks, cb) {
1829 cb->callback(return_id, (char *)return_ranges, expr);
1830 } END_FOR_EACH_PTR(cb);
1833 static void call_return_state_hooks_compare(struct expression *expr)
1835 char *return_ranges;
1836 int final_pass_orig = final_pass;
1837 sval_t sval = { .type = &int_ctype };
1838 sval_t ret;
1840 if (!get_implied_value(expr, &ret))
1841 ret.value = -1;
1843 __push_fake_cur_stree();
1845 final_pass = 0;
1846 __split_whole_condition(expr);
1847 final_pass = final_pass_orig;
1849 if (ret.value != 0) {
1850 return_ranges = alloc_sname("1");
1851 sval.value = 1;
1852 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1854 call_return_states_callbacks(return_ranges, expr);
1857 __push_true_states();
1858 __use_false_states();
1860 if (ret.value != 1) {
1861 return_ranges = alloc_sname("0");
1862 sval.value = 0;
1863 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1865 call_return_states_callbacks(return_ranges, expr);
1868 __merge_true_states();
1869 __free_fake_cur_stree();
1872 static bool is_implies_function(struct expression *expr)
1874 struct range_list *rl;
1876 if (!expr)
1877 return false;
1879 rl = get_range_implications(get_function());
1880 if (!rl)
1881 return false;
1883 sm_msg("%s: is implied", __func__);
1884 return true;
1887 static int ptr_in_list(struct sm_state *sm, struct state_list *slist)
1889 struct sm_state *tmp;
1891 FOR_EACH_PTR(slist, tmp) {
1892 if (strcmp(tmp->state->name, sm->state->name) == 0)
1893 return 1;
1894 } END_FOR_EACH_PTR(tmp);
1896 return 0;
1899 static int split_possible_helper(struct sm_state *sm, struct expression *expr)
1901 struct range_list *rl;
1902 char *return_ranges;
1903 struct sm_state *tmp;
1904 int ret = 0;
1905 int nr_possible, nr_states;
1906 char *compare_str;
1907 char buf[128];
1908 struct state_list *already_handled = NULL;
1909 sval_t sval;
1911 if (!sm || !sm->merged)
1912 return 0;
1914 if (too_many_possible(sm) && !is_implies_function(expr))
1915 return 0;
1917 /* bail if it gets too complicated */
1918 nr_possible = 0;
1919 FOR_EACH_PTR(sm->possible, tmp) {
1920 if (tmp->merged)
1921 continue;
1922 if (ptr_in_list(tmp, already_handled))
1923 continue;
1924 add_ptr_list(&already_handled, tmp);
1925 nr_possible++;
1926 } END_FOR_EACH_PTR(tmp);
1927 free_slist(&already_handled);
1928 nr_states = get_db_state_count();
1929 if (nr_states * nr_possible >= 2000 && !is_implies_function(expr))
1930 return 0;
1932 FOR_EACH_PTR(sm->possible, tmp) {
1933 if (!is_leaf(tmp))
1934 continue;
1935 if (ptr_in_list(tmp, already_handled))
1936 continue;
1937 add_ptr_list(&already_handled, tmp);
1939 ret = 1;
1940 __push_fake_cur_stree();
1942 overwrite_states_using_pool(sm, tmp);
1944 rl = cast_rl(cur_func_return_type(), estate_rl(tmp->state));
1945 return_ranges = show_rl(rl);
1946 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(clone_rl(rl)));
1947 compare_str = get_return_compare_str(expr);
1948 /* ignore obvious stuff like 0 <= param */
1949 /* Is this worthile when we have PARAM_COMPARE? */
1950 if (compare_str &&
1951 strncmp(compare_str, "[=", 2) != 0 &&
1952 rl_to_sval(rl, &sval))
1953 compare_str = NULL;
1954 if (compare_str) {
1955 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1956 return_ranges = alloc_sname(buf);
1959 call_return_states_callbacks(return_ranges, expr);
1961 __free_fake_cur_stree();
1962 } END_FOR_EACH_PTR(tmp);
1964 free_slist(&already_handled);
1966 return ret;
1969 static int call_return_state_hooks_split_possible(struct expression *expr)
1971 struct sm_state *sm;
1973 if (!expr)
1974 return 0;
1976 sm = get_returned_sm(expr);
1977 return split_possible_helper(sm, expr);
1980 static bool has_empty_state(struct sm_state *sm)
1982 struct sm_state *tmp;
1984 FOR_EACH_PTR(sm->possible, tmp) {
1985 if (!estate_rl(tmp->state))
1986 return true;
1987 } END_FOR_EACH_PTR(tmp);
1989 return false;
1992 static bool has_possible_negative(struct sm_state *sm)
1994 struct sm_state *tmp;
1996 if (!type_signed(estate_type(sm->state)))
1997 return false;
1999 FOR_EACH_PTR(sm->possible, tmp) {
2000 if (!estate_rl(tmp->state))
2001 continue;
2002 if (sval_is_negative(estate_min(tmp->state)) &&
2003 sval_is_negative(estate_max(tmp->state)))
2004 return true;
2005 } END_FOR_EACH_PTR(tmp);
2007 return false;
2010 static bool has_separate_zero_null(struct sm_state *sm)
2012 struct sm_state *tmp;
2013 sval_t sval;
2015 FOR_EACH_PTR(sm->possible, tmp) {
2016 if (!estate_get_single_value(tmp->state, &sval))
2017 continue;
2018 if (sval.value == 0)
2019 return true;
2020 } END_FOR_EACH_PTR(tmp);
2022 return false;
2025 static int split_positive_from_negative(struct expression *expr)
2027 struct sm_state *sm;
2028 struct range_list *rl;
2029 const char *return_ranges;
2030 struct range_list *ret_rl;
2031 bool separate_zero;
2032 int undo;
2034 /* We're going to print the states 3 times */
2035 if (get_db_state_count() > 10000 / 3)
2036 return 0;
2038 if (!get_implied_rl(expr, &rl) || !rl)
2039 return 0;
2040 /* Forget about INT_MAX and larger */
2041 if (rl_max(rl).value <= 0)
2042 return 0;
2043 if (!sval_is_negative(rl_min(rl)))
2044 return 0;
2046 sm = get_returned_sm(expr);
2047 if (!sm)
2048 return 0;
2049 if (has_empty_state(sm))
2050 return 0;
2051 if (!has_possible_negative(sm))
2052 return 0;
2053 separate_zero = has_separate_zero_null(sm);
2055 if (!assume(compare_expression(expr, separate_zero ? '>' : SPECIAL_GTE, zero_expr())))
2056 return 0;
2058 return_ranges = get_return_ranges_str(expr, &ret_rl);
2059 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2060 call_return_states_callbacks(return_ranges, expr);
2062 end_assume();
2064 if (separate_zero) {
2065 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
2067 return_ranges = get_return_ranges_str(expr, &ret_rl);
2068 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2069 call_return_states_callbacks(return_ranges, expr);
2071 if (undo)
2072 end_assume();
2075 undo = assume(compare_expression(expr, '<', zero_expr()));
2077 return_ranges = get_return_ranges_str(expr, &ret_rl);
2078 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2079 call_return_states_callbacks(return_ranges, expr);
2081 if (undo)
2082 end_assume();
2084 return 1;
2087 static int call_return_state_hooks_split_null_non_null_zero(struct expression *expr)
2089 struct range_list *rl;
2090 struct range_list *nonnull_rl;
2091 sval_t null_sval;
2092 struct range_list *null_rl = NULL;
2093 char *return_ranges;
2094 struct sm_state *sm;
2095 struct smatch_state *state;
2096 int nr_states;
2097 int final_pass_orig = final_pass;
2099 if (!expr || expr_equal_to_param(expr, -1))
2100 return 0;
2101 if (expr->type == EXPR_CALL)
2102 return 0;
2104 sm = get_returned_sm(expr);
2105 if (!sm)
2106 return 0;
2107 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2108 return 0;
2109 state = sm->state;
2110 if (!estate_rl(state))
2111 return 0;
2112 if (estate_min(state).value == 0 && estate_max(state).value == 0)
2113 return 0;
2114 if (has_possible_negative(sm))
2115 return 0;
2116 if (!has_separate_zero_null(sm))
2117 return 0;
2119 nr_states = get_db_state_count();
2120 if (option_info && nr_states >= 1500)
2121 return 0;
2123 rl = estate_rl(state);
2125 __push_fake_cur_stree();
2127 final_pass = 0;
2128 __split_whole_condition(expr);
2129 final_pass = final_pass_orig;
2131 nonnull_rl = rl_filter(rl, rl_zero());
2132 return_ranges = show_rl(nonnull_rl);
2133 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonnull_rl));
2135 call_return_states_callbacks(return_ranges, expr);
2137 __push_true_states();
2138 __use_false_states();
2140 return_ranges = alloc_sname("0");
2141 null_sval = sval_type_val(rl_type(rl), 0);
2142 add_range(&null_rl, null_sval, null_sval);
2143 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(null_rl));
2144 call_return_states_callbacks(return_ranges, expr);
2146 __merge_true_states();
2147 __free_fake_cur_stree();
2149 return 1;
2152 static bool is_neg_and_pos_err_code(struct range_list *rl)
2154 struct data_range *tmp, *last;
2156 if (option_project != PROJ_KERNEL)
2157 return false;
2158 if (!rl)
2159 return false;
2161 /* Assume s32min-(14),(-12)-(-1),1-s32max is an error code. */
2162 last = last_ptr_list((struct ptr_list *)rl);
2163 if (last->max.value >= 0 &&
2164 (last->min.value != 1 ||
2165 last->max.value != INT_MAX))
2166 return false;
2169 FOR_EACH_PTR(rl, tmp) {
2170 if (tmp == last)
2171 break;
2172 if (tmp->min.value != INT_MIN && tmp->min.value < -4095)
2173 return false;
2174 if (tmp->max.value < -4095 || tmp->max.value >= 0)
2175 return false;
2176 } END_FOR_EACH_PTR(tmp);
2178 return true;
2181 static bool is_kernel_success_fail(struct sm_state *sm)
2183 struct sm_state *tmp;
2184 struct range_list *rl;
2185 bool has_zero = false;
2186 bool has_neg = false;
2188 if (!sm)
2189 return false;
2191 if (!type_signed(estate_type(sm->state)))
2192 return false;
2194 FOR_EACH_PTR(sm->possible, tmp) {
2195 rl = estate_rl(tmp->state);
2196 if (!rl)
2197 return false;
2198 if (!is_leaf(tmp))
2199 continue;
2200 if (rl_min(rl).value == 0 && rl_max(rl).value == 0) {
2201 has_zero = true;
2202 continue;
2204 has_neg = true;
2205 if (is_neg_and_pos_err_code(estate_rl(tmp->state)))
2206 continue;
2207 return false;
2208 } END_FOR_EACH_PTR(tmp);
2210 return has_zero && has_neg;
2213 static int call_return_state_hooks_split_success_fail(struct expression *expr)
2215 struct expression *tmp_ret;
2216 struct sm_state *sm;
2217 struct range_list *rl;
2218 struct range_list *nonzero_rl;
2219 sval_t zero_sval;
2220 struct range_list *zero_rl = NULL;
2221 int nr_states;
2222 char *return_ranges;
2223 int final_pass_orig = final_pass;
2225 if (option_project != PROJ_KERNEL)
2226 return 0;
2228 nr_states = get_db_state_count();
2229 if (nr_states > 2000)
2230 return 0;
2232 tmp_ret = get_fake_variable(expr);
2233 if (!tmp_ret)
2234 tmp_ret = expr;
2235 sm = get_returned_sm(tmp_ret);
2236 if (!sm)
2237 return 0;
2238 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
2239 return 0;
2240 if (!is_kernel_success_fail(sm))
2241 return 0;
2243 rl = estate_rl(sm->state);
2244 if (!rl)
2245 return 0;
2247 __push_fake_cur_stree();
2249 final_pass = 0;
2250 __split_whole_condition(tmp_ret);
2251 final_pass = final_pass_orig;
2253 nonzero_rl = rl_filter(rl, rl_zero());
2254 nonzero_rl = cast_rl(cur_func_return_type(), nonzero_rl);
2255 return_ranges = show_rl(nonzero_rl);
2256 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonzero_rl));
2258 call_return_states_callbacks(return_ranges, expr);
2260 __push_true_states();
2261 __use_false_states();
2263 return_ranges = alloc_sname("0");
2264 zero_sval = sval_type_val(rl_type(rl), 0);
2265 add_range(&zero_rl, zero_sval, zero_sval);
2266 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(zero_rl));
2267 call_return_states_callbacks(return_ranges, expr);
2269 __merge_true_states();
2270 __free_fake_cur_stree();
2272 return 1;
2275 static int is_boolean(struct expression *expr)
2277 struct range_list *rl;
2279 if (!get_implied_rl(expr, &rl))
2280 return 0;
2281 if (rl_min(rl).value == 0 && rl_max(rl).value == 1)
2282 return 1;
2283 return 0;
2286 static int splitable_function_call(struct expression *expr)
2288 struct sm_state *sm;
2290 if (!expr || expr->type != EXPR_CALL)
2291 return 0;
2292 sm = get_extra_sm_state(expr);
2293 return split_possible_helper(sm, expr);
2296 static struct sm_state *find_bool_param(void)
2298 struct stree *start_states;
2299 struct symbol *arg;
2300 struct sm_state *sm, *tmp;
2301 sval_t sval;
2303 start_states = get_start_states();
2305 FOR_EACH_PTR_REVERSE(cur_func_sym->ctype.base_type->arguments, arg) {
2306 if (!arg->ident)
2307 continue;
2308 sm = get_sm_state_stree(start_states, SMATCH_EXTRA, arg->ident->name, arg);
2309 if (!sm)
2310 continue;
2311 if (rl_min(estate_rl(sm->state)).value != 0 ||
2312 rl_max(estate_rl(sm->state)).value != 1)
2313 continue;
2314 goto found;
2315 } END_FOR_EACH_PTR_REVERSE(arg);
2317 return NULL;
2319 found:
2321 * Check if it's splitable. If not, then splitting it up is likely not
2322 * useful for the callers.
2324 FOR_EACH_PTR(sm->possible, tmp) {
2325 if (is_merged(tmp))
2326 continue;
2327 if (!estate_get_single_value(tmp->state, &sval))
2328 return NULL;
2329 } END_FOR_EACH_PTR(tmp);
2331 return sm;
2334 static int split_on_bool_sm(struct sm_state *sm, struct expression *expr)
2336 struct range_list *ret_rl;
2337 const char *return_ranges;
2338 struct sm_state *tmp;
2339 int ret = 0;
2340 struct state_list *already_handled = NULL;
2342 if (!sm || !sm->merged)
2343 return 0;
2345 if (too_many_possible(sm))
2346 return 0;
2348 FOR_EACH_PTR(sm->possible, tmp) {
2349 if (tmp->merged)
2350 continue;
2351 if (ptr_in_list(tmp, already_handled))
2352 continue;
2353 add_ptr_list(&already_handled, tmp);
2355 ret = 1;
2356 __push_fake_cur_stree();
2358 overwrite_states_using_pool(sm, tmp);
2360 return_ranges = get_return_ranges_str(expr, &ret_rl);
2361 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2362 call_return_states_callbacks(return_ranges, expr);
2364 __free_fake_cur_stree();
2365 } END_FOR_EACH_PTR(tmp);
2367 free_slist(&already_handled);
2369 return ret;
2372 static int split_by_bool_param(struct expression *expr)
2374 struct sm_state *start_sm, *sm;
2375 sval_t sval;
2377 start_sm = find_bool_param();
2378 if (!start_sm)
2379 return 0;
2380 sm = get_sm_state(SMATCH_EXTRA, start_sm->name, start_sm->sym);
2381 if (!sm || estate_get_single_value(sm->state, &sval))
2382 return 0;
2384 if (get_db_state_count() * 2 >= 2000)
2385 return 0;
2387 return split_on_bool_sm(sm, expr);
2390 static int split_by_null_nonnull_param(struct expression *expr)
2392 struct symbol *arg;
2393 struct sm_state *sm;
2394 int nr_possible;
2396 arg = first_ptr_list((struct ptr_list *)cur_func_sym->ctype.base_type->arguments);
2397 if (!arg || !arg->ident)
2398 return 0;
2399 if (get_real_base_type(arg)->type != SYM_PTR)
2400 return 0;
2402 if (param_was_set_var_sym(arg->ident->name, arg))
2403 return 0;
2404 sm = get_sm_state(SMATCH_EXTRA, arg->ident->name, arg);
2405 if (!sm)
2406 return 0;
2408 if (!has_separate_zero_null(sm))
2409 return 0;
2411 nr_possible = ptr_list_size((struct ptr_list *)sm->possible);
2412 if (get_db_state_count() * nr_possible >= 2000)
2413 return 0;
2415 return split_on_bool_sm(sm, expr);
2418 static void call_hooks_based_on_pool(struct expression *expr, struct sm_state *gate_sm, struct sm_state *pool_sm)
2420 struct range_list *ret_rl;
2421 const char *return_ranges;
2423 __push_fake_cur_stree();
2425 overwrite_states_using_pool(gate_sm, pool_sm);
2427 return_ranges = get_return_ranges_str(expr, &ret_rl);
2428 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2429 call_return_states_callbacks(return_ranges, expr);
2431 __free_fake_cur_stree();
2434 static bool split_by_impossible(struct expression *expr)
2436 static int impossible_id;
2437 struct sm_state *sm, *tmp;
2438 int nr_states;
2440 if (!impossible_id)
2441 impossible_id = id_from_name("register_impossible_return");
2442 if (!impossible_id)
2443 return false;
2446 * The only states for register_impossible_return are &impossible,
2447 * &undefined and &merged. This function will break otherwise.
2450 sm = get_sm_state(impossible_id, "impossible", NULL);
2451 if (!sm || sm->state != &merged)
2452 return false;
2454 nr_states = get_db_state_count();
2455 if (nr_states >= 1000)
2456 return false;
2458 /* handle possible */
2459 FOR_EACH_PTR(sm->possible, tmp) {
2460 if (!is_leaf(tmp))
2461 continue;
2462 if (tmp->state != &undefined)
2463 continue;
2464 call_hooks_based_on_pool(expr, sm, tmp);
2465 goto impossible;
2466 } END_FOR_EACH_PTR(tmp);
2468 impossible:
2469 /* handle impossible */
2470 FOR_EACH_PTR(sm->possible, tmp) {
2471 if (!is_leaf(tmp))
2472 continue;
2473 if (strcmp(tmp->state->name, "impossible") != 0)
2474 continue;
2475 call_hooks_based_on_pool(expr, sm, tmp);
2476 return true;
2477 } END_FOR_EACH_PTR(tmp);
2479 return false;
2482 struct expression *strip_expr_statement(struct expression *expr)
2484 struct expression *orig = expr;
2485 struct statement *stmt, *last_stmt;
2487 if (!expr)
2488 return NULL;
2489 if (expr->type == EXPR_PREOP && expr->op == '(')
2490 expr = expr->unop;
2491 if (expr->type != EXPR_STATEMENT)
2492 return orig;
2493 stmt = expr->statement;
2494 if (!stmt || stmt->type != STMT_COMPOUND)
2495 return orig;
2497 last_stmt = last_ptr_list((struct ptr_list *)stmt->stmts);
2498 if (!last_stmt || last_stmt->type == STMT_LABEL)
2499 last_stmt = last_stmt->label_statement;
2500 if (!last_stmt || last_stmt->type != STMT_EXPRESSION)
2501 return orig;
2502 return strip_expr(last_stmt->expression);
2505 static bool is_kernel_error_path(struct expression *expr)
2507 struct range_list *rl;
2509 if (option_project != PROJ_KERNEL)
2510 return false;
2512 if (!get_implied_rl(expr, &rl))
2513 return false;
2514 if (rl_type(rl) != &int_ctype)
2515 return false;
2516 if (!is_neg_and_pos_err_code(rl))
2517 return false;
2518 return true;
2521 static void call_return_state_hooks(struct expression *expr)
2523 struct range_list *ret_rl;
2524 const char *return_ranges;
2525 int nr_states;
2526 sval_t sval;
2528 if (debug_db) {
2529 struct range_list *rl = NULL;
2531 get_absolute_rl(expr, &rl);
2532 sm_msg("RETURN: expr='%s' rl='%s' %lu states%s", expr_to_str(expr),
2533 show_rl(rl), stree_count(__get_cur_stree()),
2534 is_impossible_path() ? " (impossible path)" : "");
2537 if (__path_is_null())
2538 return;
2540 if (is_impossible_path())
2541 goto vanilla;
2543 if (expr && (expr->type == EXPR_COMPARE ||
2544 !get_implied_value(expr, &sval)) &&
2545 (is_condition(expr) || is_boolean(expr))) {
2546 call_return_state_hooks_compare(expr);
2547 if (debug_db)
2548 sm_msg("%s: bool", __func__);
2549 return;
2550 } else if (call_return_state_hooks_conditional(expr)) {
2551 if (debug_db)
2552 sm_msg("%s: condition", __func__);
2553 return;
2554 } else if (is_kernel_error_path(expr)) {
2555 if (debug_db)
2556 sm_msg("%s: kernel error path", __func__);
2557 goto vanilla;
2558 } else if (call_return_state_hooks_split_success_fail(expr)) {
2559 if (debug_db)
2560 sm_msg("%s: success_fail", __func__);
2561 return;
2562 } else if (call_return_state_hooks_split_possible(expr)) {
2563 if (debug_db)
2564 sm_msg("%s: split_possible", __func__);
2565 return;
2566 } else if (split_positive_from_negative(expr)) {
2567 if (debug_db)
2568 sm_msg("%s: positive negative", __func__);
2569 return;
2570 } else if (call_return_state_hooks_split_null_non_null_zero(expr)) {
2571 if (debug_db)
2572 sm_msg("%s: split zero non-zero", __func__);
2573 return;
2574 } else if (splitable_function_call(expr)) {
2575 if (debug_db)
2576 sm_msg("%s: split_function_call", __func__);
2577 return;
2578 } else if (split_by_bool_param(expr)) {
2579 if (debug_db)
2580 sm_msg("%s: bool param", __func__);
2581 return;
2582 } else if (split_by_null_nonnull_param(expr)) {
2583 if (debug_db)
2584 sm_msg("%s: null non-null param", __func__);
2585 return;
2586 } else if (split_by_impossible(expr)) {
2587 if (debug_db)
2588 sm_msg("%s: split by impossible", __func__);
2589 return;
2592 vanilla:
2593 return_ranges = get_return_ranges_str(expr, &ret_rl);
2594 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2596 nr_states = get_db_state_count();
2597 if (nr_states >= 10000) {
2598 return_id++;
2599 match_return_info(return_id, (char *)return_ranges, expr);
2600 print_limited_param_set(return_id, (char *)return_ranges, expr);
2601 mark_all_params_untracked(return_id, (char *)return_ranges, expr);
2602 return;
2604 call_return_states_callbacks(return_ranges, expr);
2605 if (debug_db)
2606 sm_msg("%s: vanilla", __func__);
2609 static void print_returned_struct_members(int return_id, char *return_ranges, struct expression *expr)
2611 struct returned_member_callback *cb;
2612 struct sm_state *sm;
2613 struct symbol *type;
2614 char *name;
2615 char member_name[256];
2616 int len;
2618 type = get_type(expr);
2619 if (!type || type->type != SYM_PTR)
2620 return;
2621 name = expr_to_var(expr);
2622 if (!name)
2623 return;
2625 len = strlen(name);
2626 FOR_EACH_PTR(returned_member_callbacks, cb) {
2627 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2628 if (sm->name[0] == '*' && strcmp(sm->name + 1, name) == 0) {
2629 strcpy(member_name, "*$");
2630 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2631 continue;
2633 if (strncmp(sm->name, name, len) != 0)
2634 continue;
2635 if (strncmp(sm->name + len, "->", 2) != 0)
2636 continue;
2637 snprintf(member_name, sizeof(member_name), "$%s", sm->name + len);
2638 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2639 } END_FOR_EACH_SM(sm);
2640 } END_FOR_EACH_PTR(cb);
2642 free_string(name);
2645 static void print_return_struct_info(int return_id, char *return_ranges,
2646 struct expression *expr,
2647 struct symbol *sym,
2648 struct return_info_callback *cb)
2650 struct sm_state *sm;
2651 const char *printed_name;
2652 int param;
2654 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2655 param = get_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2656 if (!printed_name)
2657 continue;
2658 if (param < 0)
2659 continue;
2660 cb->callback(return_id, return_ranges, expr, param, printed_name, sm);
2661 } END_FOR_EACH_SM(sm);
2663 /* always print returned states after processing param states */
2664 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2665 param = get_param_key_from_var_sym(sm->name, sm->sym, expr, &printed_name);
2666 if (!printed_name)
2667 continue;
2668 if (param != -1)
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);
3104 add_hook(&match_call_info_new, FUNCTION_CALL_HOOK);
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);
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;