db: move replace_return_ranges()
[smatch.git] / smatch_db.c
blob93458caa21cf601de6202d091bb9c9a4a6d99fbf
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);
39 #define SQLITE_CACHE_PAGES 1000
41 struct def_callback {
42 int hook_type;
43 void (*callback)(const char *name, struct symbol *sym, char *key, char *value);
45 ALLOCATOR(def_callback, "definition db hook callbacks");
46 DECLARE_PTR_LIST(callback_list, struct def_callback);
47 static struct callback_list *select_caller_info_callbacks;
49 struct member_info_callback {
50 int owner;
51 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm);
53 ALLOCATOR(member_info_callback, "caller_info callbacks");
54 DECLARE_PTR_LIST(member_info_cb_list, struct member_info_callback);
55 static struct member_info_cb_list *member_callbacks;
56 static struct member_info_cb_list *member_callbacks_new;
58 struct return_info_callback {
59 int owner;
60 void (*callback)(int return_id, char *return_ranges,
61 struct expression *returned_expr,
62 int param,
63 const char *printed_name,
64 struct sm_state *sm);
66 ALLOCATOR(return_info_callback, "return_info callbacks");
67 DECLARE_PTR_LIST(return_info_cb_list, struct return_info_callback);
68 static struct return_info_cb_list *return_callbacks;
70 struct returned_state_callback {
71 void (*callback)(int return_id, char *return_ranges, struct expression *return_expr);
73 ALLOCATOR(returned_state_callback, "returned state callbacks");
74 DECLARE_PTR_LIST(returned_state_cb_list, struct returned_state_callback);
75 static struct returned_state_cb_list *returned_state_callbacks;
77 struct returned_member_callback {
78 int owner;
79 void (*callback)(int return_id, char *return_ranges, struct expression *expr, char *printed_name, struct smatch_state *state);
81 ALLOCATOR(returned_member_callback, "returned member callbacks");
82 DECLARE_PTR_LIST(returned_member_cb_list, struct returned_member_callback);
83 static struct returned_member_cb_list *returned_member_callbacks;
85 struct db_implies_callback {
86 int type;
87 void (*callback)(struct expression *call, struct expression *arg, char *key, char *value);
89 ALLOCATOR(db_implies_callback, "return_implies callbacks");
90 DECLARE_PTR_LIST(db_implies_cb_list, struct db_implies_callback);
91 static struct db_implies_cb_list *return_implies_cb_list;
92 static struct db_implies_cb_list *call_implies_cb_list;
94 /* silently truncates if needed. */
95 char *escape_newlines(const char *str)
97 char buf[1024] = "";
98 bool found = false;
99 int i, j;
101 for (i = 0, j = 0; str[i] != '\0' && j != sizeof(buf); i++, j++) {
102 if (str[i] != '\r' && str[i] != '\n') {
103 buf[j] = str[i];
104 continue;
107 found = true;
108 buf[j++] = '\\';
109 if (j == sizeof(buf))
110 break;
111 buf[j] = 'n';
114 if (!found)
115 return alloc_sname(str);
117 if (j == sizeof(buf))
118 buf[j - 1] = '\0';
119 return alloc_sname(buf);
122 static int print_sql_output(void *unused, int argc, char **argv, char **azColName)
124 int i;
126 for (i = 0; i < argc; i++) {
127 if (i != 0)
128 sm_printf(", ");
129 sm_printf("%s", argv[i]);
131 sm_printf("\n");
132 return 0;
135 void sql_exec(struct sqlite3 *db, int (*callback)(void*, int, char**, char**), void *data, const char *sql)
137 char *err = NULL;
138 int rc;
140 if (!db)
141 return;
143 if (option_debug || debug_db) {
144 sm_msg("%s", sql);
145 if (strncasecmp(sql, "select", strlen("select")) == 0)
146 sqlite3_exec(db, sql, print_sql_output, NULL, NULL);
149 rc = sqlite3_exec(db, sql, callback, data, &err);
150 if (rc != SQLITE_OK && !parse_error) {
151 sm_ierror("%s:%d SQL error #2: %s\n", get_filename(), get_lineno(), err);
152 sm_ierror("%s:%d SQL: '%s'\n", get_filename(), get_lineno(), sql);
153 parse_error = 1;
157 static int replace_count;
158 static char **replace_table;
159 static const char *replace_return_ranges(const char *return_ranges)
161 int i;
163 if (!get_function()) {
164 /* I have no idea why EXPORT_SYMBOL() is here */
165 return return_ranges;
167 for (i = 0; i < replace_count; i += 3) {
168 if (strcmp(replace_table[i + 0], get_function()) == 0) {
169 if (strcmp(replace_table[i + 1], return_ranges) == 0)
170 return replace_table[i + 2];
173 return return_ranges;
177 static char *use_states;
178 static int get_db_state_count(void)
180 struct sm_state *sm;
181 int count = 0;
183 FOR_EACH_SM(__get_cur_stree(), sm) {
184 if (sm->owner == USHRT_MAX)
185 continue;
186 if (use_states[sm->owner])
187 count++;
188 } END_FOR_EACH_SM(sm);
189 return count;
192 static bool is_local(struct symbol *sym)
194 if (sym->ctype.modifiers & MOD_STATIC)
195 return true;
196 if ((sym->ctype.modifiers & MOD_EXTERN) &&
197 (sym->ctype.modifiers & MOD_INLINE))
198 return true;
200 if (!sym->definition)
201 return false;
203 if ((sym->definition->ctype.modifiers & MOD_EXTERN) &&
204 (sym->definition->ctype.modifiers & MOD_INLINE))
205 return true;
207 return false;
210 void db_ignore_states(int id)
212 use_states[id] = 0;
215 unsigned long long __fn_mtag;
216 static void set_fn_mtag(struct symbol *sym)
218 char buf[128];
220 if (is_local(cur_func_sym))
221 snprintf(buf, sizeof(buf), "%s %s", get_base_file(), get_function());
222 else
223 snprintf(buf, sizeof(buf), "extern %s", get_function());
225 __fn_mtag = str_to_mtag(buf);
228 void sql_insert_return_states(int return_id, const char *return_ranges,
229 int type, int param, const char *key, const char *value)
231 unsigned long long id;
234 if (key && strlen(key) >= 80)
235 return;
236 if (__inline_fn)
237 id = (unsigned long)__inline_fn;
238 else
239 id = __fn_mtag;
241 sql_insert(return_states, "'%s', '%s', %llu, %d, '%s', %d, %d, %d, '%s', '%s'",
242 get_base_file(), get_function(), id, return_id,
243 return_ranges, fn_static(), type, param, key, value);
246 static struct string_list *common_funcs;
247 static int is_common_function(const char *fn)
249 char *tmp;
251 if (!fn)
252 return 0;
254 if (strncmp(fn, "__builtin_", 10) == 0)
255 return 1;
257 FOR_EACH_PTR(common_funcs, tmp) {
258 if (strcmp(tmp, fn) == 0)
259 return 1;
260 } END_FOR_EACH_PTR(tmp);
262 return 0;
265 static char *function_signature(void)
267 return type_to_str(get_real_base_type(cur_func_sym));
270 void sql_insert_caller_info(struct expression *call, int type,
271 int param, const char *key, const char *value)
273 FILE *tmp_fd = sm_outfd;
274 char *fn;
276 if (!option_info && !__inline_call)
277 return;
278 if (unreachable())
279 return;
281 if (key && strlen(key) >= 80)
282 return;
284 fn = get_fnptr_name(call->fn);
285 if (!fn)
286 return;
288 if (__inline_call) {
289 mem_sql(NULL, NULL,
290 "insert into caller_info values ('%s', '%s', '%s', %lu, %d, %d, %d, '%s', '%s');",
291 get_base_file(), get_function(), fn, (unsigned long)call,
292 is_static(call->fn), type, param, key, value);
295 if (!option_info)
296 return;
298 if (strncmp(fn, "__builtin_", 10) == 0)
299 return;
300 if (type != INTERNAL && is_common_function(fn))
301 return;
303 sm_outfd = caller_info_fd;
304 sm_msg("SQL_caller_info: insert into caller_info values ("
305 "'%s', '%s', '%s', %%CALL_ID%%, %d, %d, %d, '%s', '%s');",
306 get_base_file(), get_function(), fn, is_static(call->fn),
307 type, param, key, value);
308 sm_outfd = tmp_fd;
310 free_string(fn);
313 void sql_insert_function_ptr(const char *fn, const char *struct_name)
315 sql_insert_or_ignore(function_ptr, "'%s', '%s', '%s', 0",
316 get_base_file(), fn, struct_name);
319 void sql_insert_return_implies(int type, int param, const char *key, const char *value)
321 sql_insert_or_ignore(return_implies, "'%s', '%s', %lu, %d, %d, %d, '%s', '%s'",
322 get_base_file(), get_function(), (unsigned long)__inline_fn,
323 fn_static(), type, param, key, value);
326 void sql_insert_call_implies(int type, int param, const char *key, const char *value)
328 sql_insert_or_ignore(call_implies, "'%s', '%s', %lu, %d, %d, %d, '%s', '%s'",
329 get_base_file(), get_function(), (unsigned long)__inline_fn,
330 fn_static(), type, param, key, value);
333 void sql_insert_function_type_size(const char *member, const char *ranges)
335 sql_insert(function_type_size, "'%s', '%s', '%s', '%s'", get_base_file(), get_function(), member, ranges);
338 void sql_insert_function_type_info(int type, const char *struct_type, const char *member, const char *value)
340 sql_insert(function_type_info, "'%s', '%s', %d, '%s', '%s', '%s'", get_base_file(), get_function(), type, struct_type, member, value);
343 void sql_insert_type_info(int type, const char *member, const char *value)
345 sql_insert_cache(type_info, "'%s', %d, '%s', '%s'", get_base_file(), type, member, value);
348 void sql_insert_local_values(const char *name, const char *value)
350 sql_insert(local_values, "'%s', '%s', '%s'", get_base_file(), name, value);
353 void sql_insert_function_type_value(const char *type, const char *value)
355 sql_insert(function_type_value, "'%s', '%s', '%s', '%s'", get_base_file(), get_function(), type, value);
358 void sql_insert_function_type(int param, const char *value)
360 sql_insert(function_type, "'%s', '%s', %d, %d, '%s'",
361 get_base_file(), get_function(), fn_static(), param, value);
364 void sql_insert_parameter_name(int param, const char *value)
366 sql_insert(parameter_name, "'%s', '%s', %d, %d, '%s'",
367 get_base_file(), get_function(), fn_static(), param, value);
370 void sql_insert_data_info(struct expression *data, int type, const char *value)
372 char *data_name;
374 data_name = get_data_info_name(data);
375 if (!data_name)
376 return;
377 sql_insert(data_info, "'%s', '%s', %d, '%s'",
378 is_static(data) ? get_base_file() : "extern",
379 data_name, type, value);
382 void sql_insert_data_info_var_sym(const char *var, struct symbol *sym, int type, const char *value)
384 sql_insert(data_info, "'%s', '%s', %d, '%s'",
385 (sym->ctype.modifiers & MOD_STATIC) ? get_base_file() : "extern",
386 var, type, value);
389 void sql_save_constraint(const char *con)
391 if (!option_info)
392 return;
394 sm_msg("SQL: insert or ignore into constraints (str) values('%s');", escape_newlines(con));
397 void sql_save_constraint_required(const char *data, int op, const char *limit)
399 sql_insert_or_ignore(constraints_required, "'%s', '%s', '%s'", data, show_special(op), limit);
402 void sql_copy_constraint_required(const char *new_limit, const char *old_limit)
404 if (!option_info)
405 return;
407 sm_msg("SQL_late: insert or ignore into constraints_required (data, op, bound) "
408 "select constraints_required.data, constraints_required.op, '%s' from "
409 "constraints_required where bound = '%s';", new_limit, old_limit);
412 void sql_insert_fn_ptr_data_link(const char *ptr, const char *data)
414 sql_insert_or_ignore(fn_ptr_data_link, "'%s', '%s'", ptr, data);
417 void sql_insert_fn_data_link(struct expression *fn, int type, int param, const char *key, const char *value)
419 if (fn->type != EXPR_SYMBOL || !fn->symbol->ident)
420 return;
422 sql_insert(fn_data_link, "'%s', '%s', %d, %d, %d, '%s', '%s'",
423 is_local(fn->symbol) ? get_base_file() : "extern",
424 fn->symbol->ident->name,
425 is_local(fn->symbol),
426 type, param, key, value);
429 void sql_insert_mtag_about(mtag_t tag, const char *left_name, const char *right_name)
431 sql_insert_cache(mtag_about, "%lld, '%s', '%s', %d, '%s', '%s'",
432 tag, get_filename(), get_function(), get_lineno(),
433 left_name, right_name);
436 void sql_insert_mtag_info(mtag_t tag, int type, const char *value)
438 sql_insert_cache(mtag_info, "'%s', %lld, %d, '%s'", get_filename(), tag, type, value);
441 void sql_insert_mtag_map(mtag_t container, int container_offset, mtag_t tag, int tag_offset)
443 sql_insert(mtag_map, "%lld, %d, %lld, %d", container, container_offset, tag, tag_offset);
446 void sql_insert_mtag_alias(mtag_t orig, mtag_t alias)
448 sql_insert(mtag_alias, "%lld, %lld", orig, alias);
451 static int save_mtag(void *_tag, int argc, char **argv, char **azColName)
453 mtag_t *saved_tag = _tag;
454 mtag_t new_tag;
456 new_tag = strtoll(argv[0], NULL, 10);
458 if (!*saved_tag)
459 *saved_tag = new_tag;
460 else if (*saved_tag != new_tag)
461 *saved_tag = -1ULL;
463 return 0;
466 int mtag_map_select_container(mtag_t tag, int container_offset, mtag_t *container)
468 mtag_t tmp = 0;
470 run_sql(save_mtag, &tmp,
471 "select container from mtag_map where tag = %lld and container_offset = %d and tag_offset = 0;",
472 tag, container_offset);
474 if (tmp == 0 || tmp == -1ULL)
475 return 0;
476 *container = tmp;
477 return 1;
480 int mtag_map_select_tag(mtag_t container, int offset, mtag_t *tag)
482 mtag_t tmp = 0;
484 run_sql(save_mtag, &tmp,
485 "select tag from mtag_map where container = %lld and container_offset = %d;",
486 container, offset);
488 if (tmp == 0 || tmp == -1ULL)
489 return 0;
490 *tag = tmp;
491 return 1;
494 char *get_static_filter(struct symbol *sym)
496 static char sql_filter[1024];
498 /* This can only happen on buggy code. Return invalid SQL. */
499 if (!sym) {
500 sql_filter[0] = '\0';
501 return sql_filter;
504 if (is_local(sym)) {
505 snprintf(sql_filter, sizeof(sql_filter),
506 "file = '%s' and function = '%s' and static = '1'",
507 get_base_file(), sym->ident->name);
508 } else {
509 snprintf(sql_filter, sizeof(sql_filter),
510 "function = '%s' and static = '0'", sym->ident->name);
513 return sql_filter;
516 static int get_row_count(void *_row_count, int argc, char **argv, char **azColName)
518 int *row_count = _row_count;
520 *row_count = 0;
521 if (argc != 1)
522 return 0;
523 *row_count = atoi(argv[0]);
524 return 0;
527 static void mark_call_params_untracked(struct expression *call)
529 struct expression *arg;
530 int i = 0;
532 FOR_EACH_PTR(call->args, arg) {
533 mark_untracked(call, i++, "$", NULL);
534 } END_FOR_EACH_PTR(arg);
537 static void sql_select_return_states_pointer(const char *cols,
538 struct expression *call, int (*callback)(void*, int, char**, char**), void *info)
540 char *ptr;
541 int return_count = 0;
543 ptr = get_fnptr_name(call->fn);
544 if (!ptr)
545 return;
547 run_sql(get_row_count, &return_count,
548 "select count(*) from return_states join function_ptr "
549 "where return_states.function == function_ptr.function and "
550 "ptr = '%s' and searchable = 1 and type = %d;", ptr, INTERNAL);
551 /* The magic number 100 is just from testing on the kernel. */
552 if (return_count > 100) {
553 mark_call_params_untracked(call);
554 return;
557 run_sql(callback, info,
558 "select %s from return_states join function_ptr where "
559 "return_states.function == function_ptr.function and ptr = '%s' "
560 "and searchable = 1 "
561 "order by function_ptr.file, return_states.file, return_id, type;",
562 cols, ptr);
565 static int is_local_symbol(struct expression *expr)
567 if (expr->type != EXPR_SYMBOL)
568 return 0;
569 if (expr->symbol->ctype.modifiers & (MOD_NONLOCAL | MOD_STATIC | MOD_ADDRESSABLE))
570 return 0;
571 return 1;
574 void sql_select_return_states(const char *cols, struct expression *call,
575 int (*callback)(void*, int, char**, char**), void *info)
577 struct expression *fn;
578 int row_count = 0;
580 if (is_fake_call(call))
581 return;
583 fn = strip_expr(call->fn);
584 if (fn->type != EXPR_SYMBOL || !fn->symbol || is_local_symbol(fn)) {
585 sql_select_return_states_pointer(cols, call, callback, info);
586 return;
589 if (inlinable(fn)) {
590 mem_sql(callback, info,
591 "select %s from return_states where call_id = '%lu' order by return_id, type;",
592 cols, (unsigned long)call);
593 return;
596 run_sql(get_row_count, &row_count, "select count(*) from return_states where %s;",
597 get_static_filter(fn->symbol));
598 if (row_count == 0 && fn->symbol && fn->symbol->definition)
599 set_state(my_id, "db_incomplete", NULL, &incomplete);
600 if (row_count > 3000)
601 return;
603 run_sql(callback, info, "select %s from return_states where %s order by file, return_id, type;",
604 cols, get_static_filter(fn->symbol));
607 bool db_incomplete(void)
609 return !!get_state(my_id, "db_incomplete", NULL);
612 #define CALL_IMPLIES 0
613 #define RETURN_IMPLIES 1
615 struct implies_info {
616 int type;
617 struct db_implies_cb_list *cb_list;
618 struct expression *expr;
619 struct symbol *sym;
622 void sql_select_implies(const char *cols, struct implies_info *info,
623 int (*callback)(void*, int, char**, char**))
625 if (info->type == RETURN_IMPLIES && inlinable(info->expr->fn)) {
626 mem_sql(callback, info,
627 "select %s from return_implies where call_id = '%lu';",
628 cols, (unsigned long)info->expr);
629 return;
632 run_sql(callback, info, "select %s from %s_implies where %s;",
633 cols,
634 info->type == CALL_IMPLIES ? "call" : "return",
635 get_static_filter(info->sym));
638 struct select_caller_info_data {
639 struct stree *final_states;
640 struct timeval start_time;
641 int prev_func_id;
642 int ignore;
643 int results;
646 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName);
648 static void sql_select_caller_info(struct select_caller_info_data *data,
649 const char *cols, struct symbol *sym)
651 if (__inline_fn) {
652 mem_sql(caller_info_callback, data,
653 "select %s from caller_info where call_id = %lu;",
654 cols, (unsigned long)__inline_fn);
655 return;
658 if (sym->ident->name && is_common_function(sym->ident->name))
659 return;
660 run_sql(caller_info_callback, data,
661 "select %s from common_caller_info where %s order by call_id;",
662 cols, get_static_filter(sym));
663 if (data->results)
664 return;
666 run_sql(caller_info_callback, data,
667 "select %s from caller_info where %s order by call_id;",
668 cols, get_static_filter(sym));
671 void select_caller_info_hook(void (*callback)(const char *name, struct symbol *sym, char *key, char *value), int type)
673 struct def_callback *def_callback = __alloc_def_callback(0);
675 def_callback->hook_type = type;
676 def_callback->callback = callback;
677 add_ptr_list(&select_caller_info_callbacks, def_callback);
681 * These call backs are used when the --info option is turned on to print struct
682 * member information. For example foo->bar could have a state in
683 * smatch_extra.c and also check_user.c.
685 void add_member_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
687 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
689 member_callback->owner = owner;
690 member_callback->callback = callback;
691 add_ptr_list(&member_callbacks, member_callback);
694 void add_caller_info_callback(int owner, void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm))
696 struct member_info_callback *member_callback = __alloc_member_info_callback(0);
698 member_callback->owner = owner;
699 member_callback->callback = callback;
700 add_ptr_list(&member_callbacks_new, member_callback);
703 void add_return_info_callback(int owner,
704 void (*callback)(int return_id, char *return_ranges,
705 struct expression *returned_expr,
706 int param,
707 const char *printed_name,
708 struct sm_state *sm))
710 struct return_info_callback *return_callback = __alloc_return_info_callback(0);
712 return_callback->owner = owner;
713 return_callback->callback = callback;
714 add_ptr_list(&return_callbacks, return_callback);
717 void add_split_return_callback(void (*fn)(int return_id, char *return_ranges, struct expression *returned_expr))
719 struct returned_state_callback *callback = __alloc_returned_state_callback(0);
721 callback->callback = fn;
722 add_ptr_list(&returned_state_callbacks, callback);
725 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))
727 struct returned_member_callback *member_callback = __alloc_returned_member_callback(0);
729 member_callback->owner = owner;
730 member_callback->callback = callback;
731 add_ptr_list(&returned_member_callbacks, member_callback);
734 void select_call_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
736 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
738 cb->type = type;
739 cb->callback = callback;
740 add_ptr_list(&call_implies_cb_list, cb);
743 void select_return_implies_hook(int type, void (*callback)(struct expression *call, struct expression *arg, char *key, char *value))
745 struct db_implies_callback *cb = __alloc_db_implies_callback(0);
747 cb->type = type;
748 cb->callback = callback;
749 add_ptr_list(&return_implies_cb_list, cb);
752 struct return_info {
753 struct expression *static_returns_call;
754 struct symbol *return_type;
755 struct range_list *return_range_list;
758 static int db_return_callback(void *_ret_info, int argc, char **argv, char **azColName)
760 struct return_info *ret_info = _ret_info;
761 struct range_list *rl;
762 struct expression *call_expr = ret_info->static_returns_call;
764 if (argc != 1)
765 return 0;
766 call_results_to_rl(call_expr, ret_info->return_type, argv[0], &rl);
767 ret_info->return_range_list = rl_union(ret_info->return_range_list, rl);
768 return 0;
771 struct range_list *db_return_vals(struct expression *expr)
773 struct return_info ret_info = {};
774 struct sm_state *sm;
776 if (is_fake_call(expr))
777 return NULL;
779 sm = get_extra_sm_state(expr);
780 if (sm)
781 return clone_rl(estate_rl(sm->state));
782 ret_info.static_returns_call = expr;
783 ret_info.return_type = get_type(expr);
784 if (!ret_info.return_type)
785 return NULL;
787 if (expr->fn->type != EXPR_SYMBOL || !expr->fn->symbol)
788 return NULL;
790 ret_info.return_range_list = NULL;
791 if (inlinable(expr->fn)) {
792 mem_sql(db_return_callback, &ret_info,
793 "select distinct return from return_states where call_id = '%lu';",
794 (unsigned long)expr);
795 } else {
796 run_sql(db_return_callback, &ret_info,
797 "select distinct return from return_states where %s;",
798 get_static_filter(expr->fn->symbol));
800 return ret_info.return_range_list;
803 struct range_list *db_return_vals_from_str(const char *fn_name)
805 struct return_info ret_info;
807 ret_info.static_returns_call = NULL;
808 ret_info.return_type = &llong_ctype;
809 ret_info.return_range_list = NULL;
811 run_sql(db_return_callback, &ret_info,
812 "select distinct return from return_states where function = '%s';",
813 fn_name);
814 return ret_info.return_range_list;
818 * This is used when we have a function that takes a function pointer as a
819 * parameter. "frob(blah, blah, my_function);" We know that the return values
820 * from frob() come from my_funcion() so we want to find the possible returns
821 * of my_function(), but we don't know which arguments are passed to it.
824 struct range_list *db_return_vals_no_args(struct expression *expr)
826 struct return_info ret_info = {};
828 if (!expr || expr->type != EXPR_SYMBOL)
829 return NULL;
831 ret_info.static_returns_call = expr;
832 ret_info.return_type = get_type(expr);
833 ret_info.return_type = get_real_base_type(ret_info.return_type);
834 if (!ret_info.return_type)
835 return NULL;
837 run_sql(db_return_callback, &ret_info,
838 "select distinct return from return_states where %s;",
839 get_static_filter(expr->symbol));
841 return ret_info.return_range_list;
844 static void match_call_marker(struct expression *expr)
846 struct symbol *type;
848 type = get_type(expr->fn);
849 if (type && type->type == SYM_PTR)
850 type = get_real_base_type(type);
853 * we just want to record something in the database so that if we have
854 * two calls like: frob(4); frob(some_unkown); then on the receiving
855 * side we know that sometimes frob is called with unknown parameters.
858 sql_insert_caller_info(expr, INTERNAL, -1, "%call_marker%", type_to_str(type));
861 int is_recursive_member(const char *name)
863 char buf[256];
864 const char *p, *next;
865 int size;
867 p = strchr(name, '>');
868 if (!p)
869 return 0;
870 p++;
871 while (true) {
872 next = strchr(p, '>');
873 if (!next)
874 return 0;
875 next++;
877 size = next - p;
878 if (size >= sizeof(buf))
879 return 0;
880 memcpy(buf, p, size);
881 buf[size] = '\0';
882 if (strstr(next, buf))
883 return 1;
884 p = next;
888 char *sm_to_arg_name(struct expression *expr, struct sm_state *sm)
890 struct symbol *sym;
891 const char *sm_name;
892 char *name;
893 bool is_address = false;
894 bool add_star = false;
895 char buf[256];
896 char *ret = NULL;
897 int len;
899 expr = strip_expr(expr);
900 if (!expr)
901 return NULL;
903 if (expr->type == EXPR_PREOP && expr->op == '&') {
904 expr = strip_expr(expr->unop);
905 is_address = true;
908 name = expr_to_var_sym(expr, &sym);
909 if (!name || !sym)
910 goto free;
911 if (sym != sm->sym)
912 goto free;
914 sm_name = sm->name;
915 add_star = false;
916 if (sm_name[0] == '*') {
917 add_star = true;
918 sm_name++;
921 len = strlen(name);
922 if (strncmp(name, sm_name, len) != 0)
923 goto free;
924 if (sm_name[len] == '\0') {
925 snprintf(buf, sizeof(buf), "%s%s$",
926 add_star ? "*" : "", is_address ? "*" : "");
927 } else {
928 if (sm_name[len] != '.' && sm_name[len] != '-')
929 goto free;
930 if (sm_name[len] == '-')
931 len++;
932 // FIXME does is_address really imply that sm_name[len] == '-'
933 snprintf(buf, sizeof(buf), "%s$->%s", add_star ? "*" : "",
934 sm_name + len);
937 ret = alloc_sname(buf);
938 free:
939 free_string(name);
940 return ret;
943 static void print_struct_members(struct expression *call, struct expression *expr, int param,
944 int owner,
945 void (*callback)(struct expression *call, int param, char *printed_name, struct sm_state *sm),
946 bool new)
948 struct sm_state *sm;
949 const char *sm_name;
950 char *name;
951 struct symbol *sym;
952 int len;
953 char printed_name[256];
954 int is_address = 0;
955 bool add_star;
956 struct symbol *type;
958 expr = strip_expr(expr);
959 if (!expr)
960 return;
961 type = get_type(expr);
962 if (!new && type && type_bits(type) < type_bits(&ulong_ctype))
963 return;
965 if (expr->type == EXPR_PREOP && expr->op == '&') {
966 expr = strip_expr(expr->unop);
967 is_address = 1;
970 name = expr_to_var_sym(expr, &sym);
971 if (!name || !sym)
972 goto free;
974 len = strlen(name);
975 FOR_EACH_SM(__get_cur_stree(), sm) {
976 if (sm->owner != owner || sm->sym != sym)
977 continue;
978 sm_name = sm->name;
979 add_star = false;
980 if (sm_name[0] == '*') {
981 add_star = true;
982 sm_name++;
984 // FIXME: simplify?
985 if (!add_star && strcmp(name, sm_name) == 0) {
986 if (is_address) {
987 snprintf(printed_name, sizeof(printed_name), "*$");
988 } else {
989 if (new)
990 snprintf(printed_name, sizeof(printed_name), "$");
991 else
992 continue;
994 } else if (add_star && strcmp(name, sm_name) == 0) {
995 snprintf(printed_name, sizeof(printed_name), "%s*$",
996 is_address ? "*" : "");
997 } else if (strncmp(name, sm_name, len) == 0) {
998 if (sm_name[len] != '.' && sm_name[len] != '-')
999 continue;
1000 if (is_address && sm_name[len] == '.') {
1001 snprintf(printed_name, sizeof(printed_name),
1002 "%s$->%s", add_star ? "*" : "",
1003 sm_name + len + 1);
1004 } else if (is_address && sm_name[len] == '-') {
1005 snprintf(printed_name, sizeof(printed_name),
1006 "%s(*$)%s", add_star ? "*" : "",
1007 sm_name + len);
1008 } else {
1009 snprintf(printed_name, sizeof(printed_name),
1010 "%s$%s", add_star ? "*" : "",
1011 sm_name + len);
1013 } else if (sm_name[0] == '&' && strncmp(name, sm_name + 1, len) == 0) {
1014 if (sm_name[len + 1] != '.' && sm_name[len + 1] != '-')
1015 continue;
1016 if (is_address && sm_name[len + 1] == '.') {
1017 snprintf(printed_name, sizeof(printed_name),
1018 "&%s$->%s", add_star ? "*" : "",
1019 sm_name + len + 2);
1020 } else if (is_address && sm_name[len] == '-') {
1021 snprintf(printed_name, sizeof(printed_name),
1022 "&%s(*$)%s", add_star ? "*" : "",
1023 sm_name + len + 1);
1024 } else {
1025 snprintf(printed_name, sizeof(printed_name),
1026 "&%s$%s", add_star ? "*" : "",
1027 sm_name + len + 1);
1029 } else {
1030 continue;
1032 if (is_recursive_member(printed_name))
1033 continue;
1034 callback(call, param, printed_name, sm);
1035 } END_FOR_EACH_SM(sm);
1036 free:
1037 free_string(name);
1040 static void match_call_info(struct expression *call)
1042 struct member_info_callback *cb;
1043 struct expression *arg;
1044 int i;
1046 FOR_EACH_PTR(member_callbacks, cb) {
1047 i = -1;
1048 FOR_EACH_PTR(call->args, arg) {
1049 i++;
1050 print_struct_members(call, arg, i, cb->owner, cb->callback, 0);
1051 } END_FOR_EACH_PTR(arg);
1052 } END_FOR_EACH_PTR(cb);
1055 static struct expression *get_fake_variable(struct expression *expr)
1057 struct expression *tmp;
1059 tmp = expr_get_fake_parent_expr(expr);
1060 if (!tmp || tmp->type != EXPR_ASSIGNMENT)
1061 return NULL;
1063 return tmp->left;
1066 static void match_call_info_new(struct expression *call)
1068 struct member_info_callback *cb;
1069 struct expression *arg, *tmp;
1070 int i;
1072 if (!option_info && !__inline_call)
1073 return;
1075 FOR_EACH_PTR(member_callbacks_new, cb) {
1076 i = -1;
1077 FOR_EACH_PTR(call->args, arg) {
1078 i++;
1079 tmp = get_fake_variable(arg);
1080 if (!tmp)
1081 tmp = arg;
1082 __ignore_param_used++;
1083 print_struct_members(call, tmp, i, cb->owner, cb->callback, 1);
1084 __ignore_param_used--;
1085 } END_FOR_EACH_PTR(arg);
1086 } END_FOR_EACH_PTR(cb);
1089 static int get_param(int param, char **name, struct symbol **sym)
1091 struct symbol *arg;
1092 int i;
1094 i = 0;
1095 FOR_EACH_PTR(cur_func_sym->ctype.base_type->arguments, arg) {
1097 * this is a temporary hack to work around a bug (I think in sparse?)
1098 * 2.6.37-rc1:fs/reiserfs/journal.o
1099 * If there is a function definition without parameter name found
1100 * after a function implementation then it causes a crash.
1101 * int foo() {}
1102 * int bar(char *);
1104 if (arg->ident->name < (char *)100)
1105 continue;
1106 if (i == param) {
1107 *name = arg->ident->name;
1108 *sym = arg;
1109 return TRUE;
1111 i++;
1112 } END_FOR_EACH_PTR(arg);
1114 return FALSE;
1117 static int function_signature_matches(const char *sig)
1119 char *my_sig;
1121 my_sig = function_signature();
1122 if (!sig || !my_sig)
1123 return 1; /* default to matching */
1124 if (strcmp(my_sig, sig) == 0)
1125 return 1;
1126 return 0;
1129 static int caller_info_callback(void *_data, int argc, char **argv, char **azColName)
1131 struct select_caller_info_data *data = _data;
1132 int func_id;
1133 long type;
1134 long param;
1135 char *key;
1136 char *value;
1137 char *name = NULL;
1138 struct symbol *sym = NULL;
1139 struct def_callback *def_callback;
1140 struct stree *stree;
1141 struct timeval cur_time;
1143 data->results = 1;
1145 if (argc != 5)
1146 return 0;
1148 gettimeofday(&cur_time, NULL);
1149 if (cur_time.tv_sec - data->start_time.tv_sec > 10)
1150 return 0;
1152 func_id = atoi(argv[0]);
1153 errno = 0;
1154 type = strtol(argv[1], NULL, 10);
1155 param = strtol(argv[2], NULL, 10);
1156 if (errno)
1157 return 0;
1158 key = argv[3];
1159 value = argv[4];
1161 if (data->prev_func_id == -1)
1162 data->prev_func_id = func_id;
1163 if (func_id != data->prev_func_id) {
1164 stree = __pop_fake_cur_stree();
1165 if (!data->ignore)
1166 merge_stree(&data->final_states, stree);
1167 free_stree(&stree);
1168 __push_fake_cur_stree();
1169 __unnullify_path();
1170 data->prev_func_id = func_id;
1171 data->ignore = 0;
1174 if (data->ignore)
1175 return 0;
1176 if (type == INTERNAL &&
1177 !function_signature_matches(value)) {
1178 data->ignore = 1;
1179 return 0;
1182 if (param >= 0 && !get_param(param, &name, &sym))
1183 return 0;
1185 FOR_EACH_PTR(select_caller_info_callbacks, def_callback) {
1186 if (def_callback->hook_type == type)
1187 def_callback->callback(name, sym, key, value);
1188 } END_FOR_EACH_PTR(def_callback);
1190 return 0;
1193 static struct string_list *ptr_names_done;
1194 static struct string_list *ptr_names;
1196 static int get_ptr_name(void *unused, int argc, char **argv, char **azColName)
1198 insert_string(&ptr_names, alloc_string(argv[0]));
1199 return 0;
1202 static char *get_next_ptr_name(void)
1204 char *ptr;
1206 FOR_EACH_PTR(ptr_names, ptr) {
1207 if (!insert_string(&ptr_names_done, ptr))
1208 continue;
1209 return ptr;
1210 } END_FOR_EACH_PTR(ptr);
1211 return NULL;
1214 static void get_ptr_names(const char *file, const char *name)
1216 char sql_filter[1024];
1217 int before, after;
1219 if (file) {
1220 snprintf(sql_filter, 1024, "file = '%s' and function = '%s';",
1221 file, name);
1222 } else {
1223 snprintf(sql_filter, 1024, "function = '%s';", name);
1226 before = ptr_list_size((struct ptr_list *)ptr_names);
1228 run_sql(get_ptr_name, NULL,
1229 "select distinct ptr from function_ptr where %s",
1230 sql_filter);
1232 after = ptr_list_size((struct ptr_list *)ptr_names);
1233 if (before == after)
1234 return;
1236 while ((name = get_next_ptr_name()))
1237 get_ptr_names(NULL, name);
1240 static void match_data_from_db(struct symbol *sym)
1242 struct select_caller_info_data data = { .prev_func_id = -1 };
1243 struct sm_state *sm;
1244 struct stree *stree;
1245 struct timeval end_time;
1247 if (!sym || !sym->ident)
1248 return;
1250 set_fn_mtag(sym);
1251 gettimeofday(&data.start_time, NULL);
1253 __push_fake_cur_stree();
1254 __unnullify_path();
1256 if (!__inline_fn) {
1257 char *ptr;
1259 if (sym->ctype.modifiers & MOD_STATIC)
1260 get_ptr_names(get_base_file(), sym->ident->name);
1261 else
1262 get_ptr_names(NULL, sym->ident->name);
1264 if (ptr_list_size((struct ptr_list *)ptr_names) > 20) {
1265 __free_ptr_list((struct ptr_list **)&ptr_names);
1266 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1267 __free_fake_cur_stree();
1268 return;
1271 sql_select_caller_info(&data,
1272 "call_id, type, parameter, key, value",
1273 sym);
1276 stree = __pop_fake_cur_stree();
1277 if (!data.ignore)
1278 merge_stree(&data.final_states, stree);
1279 free_stree(&stree);
1280 __push_fake_cur_stree();
1281 __unnullify_path();
1282 data.prev_func_id = -1;
1283 data.ignore = 0;
1284 data.results = 0;
1286 FOR_EACH_PTR(ptr_names, ptr) {
1287 run_sql(caller_info_callback, &data,
1288 "select call_id, type, parameter, key, value"
1289 " from common_caller_info where function = '%s' order by call_id",
1290 ptr);
1291 } END_FOR_EACH_PTR(ptr);
1293 if (data.results) {
1294 FOR_EACH_PTR(ptr_names, ptr) {
1295 free_string(ptr);
1296 } END_FOR_EACH_PTR(ptr);
1297 goto free_ptr_names;
1300 FOR_EACH_PTR(ptr_names, ptr) {
1301 run_sql(caller_info_callback, &data,
1302 "select call_id, type, parameter, key, value"
1303 " from caller_info where function = '%s' order by call_id",
1304 ptr);
1305 free_string(ptr);
1306 } END_FOR_EACH_PTR(ptr);
1308 free_ptr_names:
1309 __free_ptr_list((struct ptr_list **)&ptr_names);
1310 __free_ptr_list((struct ptr_list **)&ptr_names_done);
1311 } else {
1312 sql_select_caller_info(&data,
1313 "call_id, type, parameter, key, value",
1314 sym);
1317 stree = __pop_fake_cur_stree();
1318 if (!data.ignore)
1319 merge_stree(&data.final_states, stree);
1320 free_stree(&stree);
1322 gettimeofday(&end_time, NULL);
1323 if (end_time.tv_sec - data.start_time.tv_sec <= 10) {
1324 FOR_EACH_SM(data.final_states, sm) {
1325 __set_sm(sm);
1326 } END_FOR_EACH_SM(sm);
1329 free_stree(&data.final_states);
1332 static int return_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1334 struct implies_info *info = _info;
1335 struct db_implies_callback *cb;
1336 struct expression *arg = NULL;
1337 int type;
1338 int param;
1340 if (argc != 5)
1341 return 0;
1343 type = atoi(argv[1]);
1344 param = atoi(argv[2]);
1346 FOR_EACH_PTR(info->cb_list, cb) {
1347 if (cb->type != type)
1348 continue;
1349 if (param != -1) {
1350 arg = get_argument_from_call_expr(info->expr->args, param);
1351 if (!arg)
1352 continue;
1354 cb->callback(info->expr, arg, argv[3], argv[4]);
1355 } END_FOR_EACH_PTR(cb);
1357 return 0;
1360 static int call_implies_callbacks(void *_info, int argc, char **argv, char **azColName)
1362 struct implies_info *info = _info;
1363 struct db_implies_callback *cb;
1364 struct expression *arg;
1365 struct symbol *sym;
1366 char *name;
1367 int type;
1368 int param;
1370 if (argc != 5)
1371 return 0;
1373 type = atoi(argv[1]);
1374 param = atoi(argv[2]);
1376 if (!get_param(param, &name, &sym))
1377 return 0;
1378 arg = symbol_expression(sym);
1379 if (!arg)
1380 return 0;
1382 FOR_EACH_PTR(info->cb_list, cb) {
1383 if (cb->type != type)
1384 continue;
1385 cb->callback(info->expr, arg, argv[3], argv[4]);
1386 } END_FOR_EACH_PTR(cb);
1388 return 0;
1391 static void match_return_implies(struct expression *expr)
1393 struct implies_info info = {
1394 .type = RETURN_IMPLIES,
1395 .cb_list = return_implies_cb_list,
1398 if (expr->fn->type != EXPR_SYMBOL ||
1399 !expr->fn->symbol)
1400 return;
1401 info.expr = expr;
1402 info.sym = expr->fn->symbol;
1403 sql_select_implies("function, type, parameter, key, value", &info,
1404 return_implies_callbacks);
1407 static void match_call_implies(struct symbol *sym)
1409 struct implies_info info = {
1410 .type = CALL_IMPLIES,
1411 .cb_list = call_implies_cb_list,
1414 if (!sym || !sym->ident)
1415 return;
1417 info.sym = sym;
1418 sql_select_implies("function, type, parameter, key, value", &info,
1419 call_implies_callbacks);
1422 static char *get_fn_param_str(struct expression *expr)
1424 struct expression *tmp;
1425 int param;
1426 char buf[32];
1428 tmp = get_assigned_expr(expr);
1429 if (tmp)
1430 expr = tmp;
1431 expr = strip_expr(expr);
1432 if (!expr || expr->type != EXPR_CALL)
1433 return NULL;
1434 expr = strip_expr(expr->fn);
1435 if (!expr || expr->type != EXPR_SYMBOL)
1436 return NULL;
1437 param = get_param_num(expr);
1438 if (param < 0)
1439 return NULL;
1441 snprintf(buf, sizeof(buf), "[r $%d]", param);
1442 return alloc_sname(buf);
1445 static char *get_return_compare_is_param(struct expression *expr)
1447 char *var;
1448 char buf[256];
1449 int comparison;
1450 int param;
1452 param = get_param_num(expr);
1453 if (param < 0)
1454 return NULL;
1456 var = expr_to_var(expr);
1457 if (!var)
1458 return NULL;
1459 snprintf(buf, sizeof(buf), "%s orig", var);
1460 comparison = get_comparison_strings(var, buf);
1461 free_string(var);
1463 if (!comparison)
1464 return NULL;
1466 snprintf(buf, sizeof(buf), "[%s$%d]", show_special(comparison), param);
1467 return alloc_sname(buf);
1470 static char *get_return_compare_str(struct expression *expr)
1472 char *compare_str;
1474 compare_str = get_return_compare_is_param(expr);
1475 if (compare_str)
1476 return compare_str;
1478 compare_str = expr_lte_to_param(expr, -1);
1479 if (compare_str)
1480 return compare_str;
1482 return expr_param_comparison(expr, -1);
1485 static const char *get_return_ranges_str(struct expression *expr, struct range_list **rl_p)
1487 struct range_list *rl;
1488 char *return_ranges;
1489 sval_t sval;
1490 char *fn_param_str;
1491 char *compare_str;
1492 char *math_str;
1493 char buf[128];
1495 *rl_p = NULL;
1497 if (!expr)
1498 return alloc_sname("");
1500 if (get_implied_value(expr, &sval)) {
1501 sval = sval_cast(cur_func_return_type(), sval);
1502 *rl_p = alloc_rl(sval, sval);
1503 return sval_to_str_or_err_ptr(sval);
1506 fn_param_str = get_fn_param_str(expr);
1507 compare_str = expr_equal_to_param(expr, -1);
1508 math_str = get_value_in_terms_of_parameter_math(expr);
1510 if (get_implied_rl(expr, &rl) && !is_whole_rl(rl)) {
1511 rl = cast_rl(cur_func_return_type(), rl);
1512 return_ranges = show_rl(rl);
1513 } else if (get_imaginary_absolute(expr, &rl)){
1514 rl = cast_rl(cur_func_return_type(), rl);
1515 return alloc_sname(show_rl(rl));
1516 } else {
1517 get_absolute_rl(expr, &rl);
1518 rl = cast_rl(cur_func_return_type(), rl);
1519 return_ranges = show_rl(rl);
1521 *rl_p = rl;
1523 if (fn_param_str) {
1524 snprintf(buf, sizeof(buf), "%s%s", return_ranges, fn_param_str);
1525 return alloc_sname(buf);
1527 if (compare_str) {
1528 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1529 return alloc_sname(buf);
1531 if (math_str) {
1532 snprintf(buf, sizeof(buf), "%s[%s]", return_ranges, math_str);
1533 return alloc_sname(buf);
1535 compare_str = get_return_compare_str(expr);
1536 if (compare_str) {
1537 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1538 return alloc_sname(buf);
1541 return return_ranges;
1544 static void match_return_info(int return_id, char *return_ranges, struct expression *expr)
1546 sql_insert_return_states(return_id, return_ranges, INTERNAL, -1, "", function_signature());
1549 static bool call_return_state_hooks_conditional(struct expression *expr)
1551 int final_pass_orig = final_pass;
1552 static int recurse;
1554 if (recurse >= 2)
1555 return false;
1556 if (!expr ||
1557 (expr->type != EXPR_CONDITIONAL && expr->type != EXPR_SELECT))
1558 return false;
1560 recurse++;
1562 __push_fake_cur_stree();
1564 final_pass = 0;
1565 __split_whole_condition(expr->conditional);
1566 final_pass = final_pass_orig;
1568 call_return_state_hooks(expr->cond_true ?: expr->conditional);
1570 __push_true_states();
1571 __use_false_states();
1573 call_return_state_hooks(expr->cond_false);
1575 __merge_true_states();
1576 __free_fake_cur_stree();
1578 recurse--;
1579 return true;
1582 static void call_return_states_hooks(char *return_ranges, struct expression *expr)
1584 struct returned_state_callback *cb;
1586 return_ranges = replace_return_ranges(return_ranges);
1587 return_id++;
1588 FOR_EACH_PTR(returned_state_callbacks, cb) {
1589 cb->callback(return_id, return_ranges, expr);
1590 } END_FOR_EACH_PTR(cb);
1593 static void call_return_state_hooks_compare(struct expression *expr)
1595 char *return_ranges;
1596 int final_pass_orig = final_pass;
1597 sval_t sval = { .type = &int_ctype };
1598 sval_t ret;
1600 if (!get_implied_value(expr, &ret))
1601 ret.value = -1;
1603 __push_fake_cur_stree();
1605 final_pass = 0;
1606 __split_whole_condition(expr);
1607 final_pass = final_pass_orig;
1609 if (ret.value != 0) {
1610 return_ranges = alloc_sname("1");
1611 sval.value = 1;
1612 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1614 call_return_states_hooks(return_ranges, expr);
1617 __push_true_states();
1618 __use_false_states();
1620 if (ret.value != 1) {
1621 return_ranges = alloc_sname("0");
1622 sval.value = 0;
1623 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_sval(sval));
1625 call_return_states_hooks(return_ranges, expr);
1628 __merge_true_states();
1629 __free_fake_cur_stree();
1632 static bool is_implies_function(struct expression *expr)
1634 struct range_list *rl;
1636 if (!expr)
1637 return false;
1639 rl = get_range_implications(get_function());
1640 if (!rl)
1641 return false;
1643 sm_msg("%s: is implied", __func__);
1644 return true;
1647 static int ptr_in_list(struct sm_state *sm, struct state_list *slist)
1649 struct sm_state *tmp;
1651 FOR_EACH_PTR(slist, tmp) {
1652 if (strcmp(tmp->state->name, sm->state->name) == 0)
1653 return 1;
1654 } END_FOR_EACH_PTR(tmp);
1656 return 0;
1659 static int split_possible_helper(struct sm_state *sm, struct expression *expr)
1661 struct range_list *rl;
1662 char *return_ranges;
1663 struct sm_state *tmp;
1664 int ret = 0;
1665 int nr_possible, nr_states;
1666 char *compare_str;
1667 char buf[128];
1668 struct state_list *already_handled = NULL;
1669 sval_t sval;
1671 if (!sm || !sm->merged)
1672 return 0;
1674 if (too_many_possible(sm) && !is_implies_function(expr))
1675 return 0;
1677 /* bail if it gets too complicated */
1678 nr_possible = 0;
1679 FOR_EACH_PTR(sm->possible, tmp) {
1680 if (tmp->merged)
1681 continue;
1682 if (ptr_in_list(tmp, already_handled))
1683 continue;
1684 add_ptr_list(&already_handled, tmp);
1685 nr_possible++;
1686 } END_FOR_EACH_PTR(tmp);
1687 free_slist(&already_handled);
1688 nr_states = get_db_state_count();
1689 if (nr_states * nr_possible >= 2000 && !is_implies_function(expr))
1690 return 0;
1692 FOR_EACH_PTR(sm->possible, tmp) {
1693 if (tmp->merged)
1694 continue;
1695 if (ptr_in_list(tmp, already_handled))
1696 continue;
1697 add_ptr_list(&already_handled, tmp);
1699 ret = 1;
1700 __push_fake_cur_stree();
1702 overwrite_states_using_pool(sm, tmp);
1704 rl = cast_rl(cur_func_return_type(), estate_rl(tmp->state));
1705 return_ranges = show_rl(rl);
1706 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(clone_rl(rl)));
1707 compare_str = get_return_compare_str(expr);
1708 /* ignore obvious stuff like 0 <= param */
1709 /* Is this worthile when we have PARAM_COMPARE? */
1710 if (compare_str &&
1711 strncmp(compare_str, "[=", 2) != 0 &&
1712 rl_to_sval(rl, &sval))
1713 compare_str = NULL;
1714 if (compare_str) {
1715 snprintf(buf, sizeof(buf), "%s%s", return_ranges, compare_str);
1716 return_ranges = alloc_sname(buf);
1719 call_return_states_hooks(return_ranges, expr);
1721 __free_fake_cur_stree();
1722 } END_FOR_EACH_PTR(tmp);
1724 free_slist(&already_handled);
1726 return ret;
1729 static int call_return_state_hooks_split_possible(struct expression *expr)
1731 struct expression *fake;
1732 struct sm_state *sm;
1734 if (!expr)
1735 return 0;
1737 sm = get_sm_state_expr(SMATCH_EXTRA, expr);
1738 if (!sm) {
1739 fake = expr_get_fake_parent_expr(expr);
1740 if (!fake || fake->type != EXPR_ASSIGNMENT || fake->op != '=')
1741 return 0;
1742 fake = fake->left;
1743 sm = get_sm_state_expr(SMATCH_EXTRA, fake);
1745 return split_possible_helper(sm, expr);
1748 static bool has_possible_negative(struct sm_state *sm)
1750 struct sm_state *tmp;
1752 if (!type_signed(estate_type(sm->state)))
1753 return false;
1755 FOR_EACH_PTR(sm->possible, tmp) {
1756 if (!estate_rl(tmp->state))
1757 continue;
1758 if (sval_is_negative(estate_min(tmp->state)) &&
1759 sval_is_negative(estate_max(tmp->state)))
1760 return true;
1761 } END_FOR_EACH_PTR(tmp);
1763 return false;
1766 static bool has_separate_zero_null(struct sm_state *sm)
1768 struct sm_state *tmp;
1769 sval_t sval;
1771 FOR_EACH_PTR(sm->possible, tmp) {
1772 if (!estate_get_single_value(tmp->state, &sval))
1773 continue;
1774 if (sval.value == 0)
1775 return true;
1776 } END_FOR_EACH_PTR(tmp);
1778 return false;
1781 static int split_positive_from_negative(struct expression *expr)
1783 struct sm_state *sm;
1784 struct range_list *rl;
1785 const char *return_ranges;
1786 struct range_list *ret_rl;
1787 bool separate_zero;
1788 int undo;
1790 /* We're going to print the states 3 times */
1791 if (get_db_state_count() > 10000 / 3)
1792 return 0;
1794 if (!get_implied_rl(expr, &rl) || !rl)
1795 return 0;
1796 /* Forget about INT_MAX and larger */
1797 if (rl_max(rl).value <= 0)
1798 return 0;
1799 if (!sval_is_negative(rl_min(rl)))
1800 return 0;
1802 sm = get_sm_state_expr(SMATCH_EXTRA, expr);
1803 if (!sm)
1804 return 0;
1805 if (!has_possible_negative(sm))
1806 return 0;
1807 separate_zero = has_separate_zero_null(sm);
1809 if (!assume(compare_expression(expr, separate_zero ? '>' : SPECIAL_GTE, zero_expr())))
1810 return 0;
1812 return_ranges = get_return_ranges_str(expr, &ret_rl);
1813 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
1814 call_return_states_hooks((char *)return_ranges, expr);
1816 end_assume();
1818 if (separate_zero) {
1819 undo = assume(compare_expression(expr, SPECIAL_EQUAL, zero_expr()));
1821 return_ranges = get_return_ranges_str(expr, &ret_rl);
1822 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
1823 call_return_states_hooks((char *)return_ranges, expr);
1825 if (undo)
1826 end_assume();
1829 undo = assume(compare_expression(expr, '<', zero_expr()));
1831 return_ranges = get_return_ranges_str(expr, &ret_rl);
1832 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
1833 call_return_states_hooks((char *)return_ranges, expr);
1835 if (undo)
1836 end_assume();
1838 return 1;
1841 static int call_return_state_hooks_split_null_non_null_zero(struct expression *expr)
1843 struct range_list *rl;
1844 struct range_list *nonnull_rl;
1845 sval_t null_sval;
1846 struct range_list *null_rl = NULL;
1847 char *return_ranges;
1848 struct sm_state *sm;
1849 struct smatch_state *state;
1850 int nr_states;
1851 int final_pass_orig = final_pass;
1853 if (!expr || expr_equal_to_param(expr, -1))
1854 return 0;
1855 if (expr->type == EXPR_CALL)
1856 return 0;
1858 sm = get_sm_state_expr(SMATCH_EXTRA, expr);
1859 if (!sm)
1860 return 0;
1861 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
1862 return 0;
1863 state = sm->state;
1864 if (!estate_rl(state))
1865 return 0;
1866 if (estate_min(state).value == 0 && estate_max(state).value == 0)
1867 return 0;
1868 if (has_possible_negative(sm))
1869 return 0;
1870 if (!has_separate_zero_null(sm))
1871 return 0;
1873 nr_states = get_db_state_count();
1874 if (option_info && nr_states >= 1500)
1875 return 0;
1877 rl = estate_rl(state);
1879 __push_fake_cur_stree();
1881 final_pass = 0;
1882 __split_whole_condition(expr);
1883 final_pass = final_pass_orig;
1885 nonnull_rl = rl_filter(rl, rl_zero());
1886 return_ranges = show_rl(nonnull_rl);
1887 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonnull_rl));
1889 call_return_states_hooks(return_ranges, expr);
1891 __push_true_states();
1892 __use_false_states();
1894 return_ranges = alloc_sname("0");
1895 null_sval = sval_type_val(rl_type(rl), 0);
1896 add_range(&null_rl, null_sval, null_sval);
1897 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(null_rl));
1898 call_return_states_hooks(return_ranges, expr);
1900 __merge_true_states();
1901 __free_fake_cur_stree();
1903 return 1;
1906 static bool is_kernel_success_fail(struct sm_state *sm)
1908 struct sm_state *tmp;
1909 struct range_list *rl;
1910 bool has_zero = false;
1911 bool has_neg = false;
1913 if (!type_signed(estate_type(sm->state)))
1914 return false;
1916 FOR_EACH_PTR(sm->possible, tmp) {
1917 rl = estate_rl(tmp->state);
1918 if (!rl)
1919 return false;
1920 if (rl_min(rl).value == 0 && rl_max(rl).value == 0) {
1921 has_zero = true;
1922 continue;
1924 has_neg = true;
1925 if (rl_min(rl).value >= -4095 && rl_max(rl).value < 0)
1926 continue;
1927 if (strcmp(tmp->state->name, "s32min-(-1)") == 0)
1928 continue;
1929 if (strcmp(tmp->state->name, "s32min-(-1),1-s32max") == 0)
1930 continue;
1931 return false;
1932 } END_FOR_EACH_PTR(tmp);
1934 return has_zero && has_neg;
1937 static int call_return_state_hooks_split_success_fail(struct expression *expr)
1939 struct sm_state *sm;
1940 struct range_list *rl;
1941 struct range_list *nonzero_rl;
1942 sval_t zero_sval;
1943 struct range_list *zero_rl = NULL;
1944 int nr_states;
1945 char *return_ranges;
1946 int final_pass_orig = final_pass;
1948 if (option_project != PROJ_KERNEL)
1949 return 0;
1951 nr_states = get_db_state_count();
1952 if (nr_states > 2000)
1953 return 0;
1955 sm = get_sm_state_expr(SMATCH_EXTRA, expr);
1956 if (!sm)
1957 return 0;
1958 if (ptr_list_size((struct ptr_list *)sm->possible) == 1)
1959 return 0;
1960 if (!is_kernel_success_fail(sm))
1961 return 0;
1963 rl = estate_rl(sm->state);
1964 if (!rl)
1965 return 0;
1967 __push_fake_cur_stree();
1969 final_pass = 0;
1970 __split_whole_condition(expr);
1971 final_pass = final_pass_orig;
1973 nonzero_rl = rl_filter(rl, rl_zero());
1974 nonzero_rl = cast_rl(cur_func_return_type(), nonzero_rl);
1975 return_ranges = show_rl(nonzero_rl);
1976 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(nonzero_rl));
1978 call_return_states_hooks(return_ranges, expr);
1980 __push_true_states();
1981 __use_false_states();
1983 return_ranges = alloc_sname("0");
1984 zero_sval = sval_type_val(rl_type(rl), 0);
1985 add_range(&zero_rl, zero_sval, zero_sval);
1986 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(zero_rl));
1987 call_return_states_hooks(return_ranges, expr);
1989 __merge_true_states();
1990 __free_fake_cur_stree();
1992 return 1;
1995 static int is_boolean(struct expression *expr)
1997 struct range_list *rl;
1999 if (!get_implied_rl(expr, &rl))
2000 return 0;
2001 if (rl_min(rl).value == 0 && rl_max(rl).value == 1)
2002 return 1;
2003 return 0;
2006 static int splitable_function_call(struct expression *expr)
2008 struct sm_state *sm;
2010 if (!expr || expr->type != EXPR_CALL)
2011 return 0;
2012 sm = get_extra_sm_state(expr);
2013 return split_possible_helper(sm, expr);
2016 static struct sm_state *find_bool_param(void)
2018 struct stree *start_states;
2019 struct symbol *arg;
2020 struct sm_state *sm, *tmp;
2021 sval_t sval;
2023 start_states = get_start_states();
2025 FOR_EACH_PTR_REVERSE(cur_func_sym->ctype.base_type->arguments, arg) {
2026 if (!arg->ident)
2027 continue;
2028 sm = get_sm_state_stree(start_states, SMATCH_EXTRA, arg->ident->name, arg);
2029 if (!sm)
2030 continue;
2031 if (rl_min(estate_rl(sm->state)).value != 0 ||
2032 rl_max(estate_rl(sm->state)).value != 1)
2033 continue;
2034 goto found;
2035 } END_FOR_EACH_PTR_REVERSE(arg);
2037 return NULL;
2039 found:
2041 * Check if it's splitable. If not, then splitting it up is likely not
2042 * useful for the callers.
2044 FOR_EACH_PTR(sm->possible, tmp) {
2045 if (is_merged(tmp))
2046 continue;
2047 if (!estate_get_single_value(tmp->state, &sval))
2048 return NULL;
2049 } END_FOR_EACH_PTR(tmp);
2051 return sm;
2054 static int split_on_bool_sm(struct sm_state *sm, struct expression *expr)
2056 struct range_list *ret_rl;
2057 const char *return_ranges;
2058 struct sm_state *tmp;
2059 int ret = 0;
2060 struct state_list *already_handled = NULL;
2062 if (!sm || !sm->merged)
2063 return 0;
2065 if (too_many_possible(sm))
2066 return 0;
2068 FOR_EACH_PTR(sm->possible, tmp) {
2069 if (tmp->merged)
2070 continue;
2071 if (ptr_in_list(tmp, already_handled))
2072 continue;
2073 add_ptr_list(&already_handled, tmp);
2075 ret = 1;
2076 __push_fake_cur_stree();
2078 overwrite_states_using_pool(sm, tmp);
2080 return_ranges = get_return_ranges_str(expr, &ret_rl);
2081 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2082 call_return_states_hooks((char *)return_ranges, expr);
2084 __free_fake_cur_stree();
2085 } END_FOR_EACH_PTR(tmp);
2087 free_slist(&already_handled);
2089 return ret;
2092 static int split_by_bool_param(struct expression *expr)
2094 struct sm_state *start_sm, *sm;
2095 sval_t sval;
2097 start_sm = find_bool_param();
2098 if (!start_sm)
2099 return 0;
2100 sm = get_sm_state(SMATCH_EXTRA, start_sm->name, start_sm->sym);
2101 if (!sm || estate_get_single_value(sm->state, &sval))
2102 return 0;
2104 if (get_db_state_count() * 2 >= 2000)
2105 return 0;
2107 return split_on_bool_sm(sm, expr);
2110 static int split_by_null_nonnull_param(struct expression *expr)
2112 struct symbol *arg;
2113 struct sm_state *sm;
2114 int nr_possible;
2116 /* function must only take one pointer */
2117 if (ptr_list_size((struct ptr_list *)cur_func_sym->ctype.base_type->arguments) != 1)
2118 return 0;
2119 arg = first_ptr_list((struct ptr_list *)cur_func_sym->ctype.base_type->arguments);
2120 if (!arg->ident)
2121 return 0;
2122 if (get_real_base_type(arg)->type != SYM_PTR)
2123 return 0;
2125 if (param_was_set_var_sym(arg->ident->name, arg))
2126 return 0;
2127 sm = get_sm_state(SMATCH_EXTRA, arg->ident->name, arg);
2128 if (!sm)
2129 return 0;
2131 if (!has_separate_zero_null(sm))
2132 return 0;
2134 nr_possible = ptr_list_size((struct ptr_list *)sm->possible);
2135 if (get_db_state_count() * nr_possible >= 2000)
2136 return 0;
2138 return split_on_bool_sm(sm, expr);
2141 struct expression *strip_expr_statement(struct expression *expr)
2143 struct expression *orig = expr;
2144 struct statement *stmt, *last_stmt;
2146 if (!expr)
2147 return NULL;
2148 if (expr->type == EXPR_PREOP && expr->op == '(')
2149 expr = expr->unop;
2150 if (expr->type != EXPR_STATEMENT)
2151 return orig;
2152 stmt = expr->statement;
2153 if (!stmt || stmt->type != STMT_COMPOUND)
2154 return orig;
2156 last_stmt = last_ptr_list((struct ptr_list *)stmt->stmts);
2157 if (!last_stmt || last_stmt->type == STMT_LABEL)
2158 last_stmt = last_stmt->label_statement;
2159 if (!last_stmt || last_stmt->type != STMT_EXPRESSION)
2160 return orig;
2161 return strip_expr(last_stmt->expression);
2164 static bool is_kernel_error_path(struct expression *expr)
2166 struct range_list *rl;
2169 * Splitting up returns requires resources. It also requires resources
2170 * for the caller. It doesn't seem worth it to split anything up.
2172 if (!get_implied_rl(expr, &rl))
2173 return false;
2174 if (rl_type(rl) != &int_ctype)
2175 return false;
2176 if (rl_min(rl).value >= -4095 &&
2177 rl_max(rl).value < 0)
2178 return true;
2179 return false;
2182 static void call_return_state_hooks(struct expression *expr)
2184 struct range_list *ret_rl;
2185 const char *return_ranges;
2186 int nr_states;
2187 sval_t sval;
2189 if (__path_is_null())
2190 return;
2192 expr = strip_expr(expr);
2193 expr = strip_expr_statement(expr);
2195 if (is_impossible_path())
2196 goto vanilla;
2198 if (expr && (expr->type == EXPR_COMPARE ||
2199 !get_implied_value(expr, &sval)) &&
2200 (is_condition(expr) || is_boolean(expr))) {
2201 call_return_state_hooks_compare(expr);
2202 return;
2203 } else if (call_return_state_hooks_conditional(expr)) {
2204 return;
2205 } else if (is_kernel_error_path(expr)) {
2206 goto vanilla;
2207 } else if (call_return_state_hooks_split_possible(expr)) {
2208 return;
2209 } else if (split_positive_from_negative(expr)) {
2210 return;
2211 } else if (call_return_state_hooks_split_null_non_null_zero(expr)) {
2212 return;
2213 } else if (call_return_state_hooks_split_success_fail(expr)) {
2214 return;
2215 } else if (splitable_function_call(expr)) {
2216 return;
2217 } else if (split_by_bool_param(expr)) {
2218 } else if (split_by_null_nonnull_param(expr)) {
2219 return;
2222 vanilla:
2223 return_ranges = get_return_ranges_str(expr, &ret_rl);
2224 set_state(RETURN_ID, "return_ranges", NULL, alloc_estate_rl(ret_rl));
2226 nr_states = get_db_state_count();
2227 if (nr_states >= 10000) {
2228 return_id++;
2229 match_return_info(return_id, (char *)return_ranges, expr);
2230 print_limited_param_set(return_id, (char *)return_ranges, expr);
2231 mark_all_params_untracked(return_id, (char *)return_ranges, expr);
2232 return;
2234 call_return_states_hooks((char *)return_ranges, expr);
2237 static void print_returned_struct_members(int return_id, char *return_ranges, struct expression *expr)
2239 struct returned_member_callback *cb;
2240 struct sm_state *sm;
2241 struct symbol *type;
2242 char *name;
2243 char member_name[256];
2244 int len;
2246 type = get_type(expr);
2247 if (!type || type->type != SYM_PTR)
2248 return;
2249 name = expr_to_var(expr);
2250 if (!name)
2251 return;
2253 len = strlen(name);
2254 FOR_EACH_PTR(returned_member_callbacks, cb) {
2255 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2256 if (sm->name[0] == '*' && strcmp(sm->name + 1, name) == 0) {
2257 strcpy(member_name, "*$");
2258 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2259 continue;
2261 if (strncmp(sm->name, name, len) != 0)
2262 continue;
2263 if (strncmp(sm->name + len, "->", 2) != 0)
2264 continue;
2265 snprintf(member_name, sizeof(member_name), "$%s", sm->name + len);
2266 cb->callback(return_id, return_ranges, expr, member_name, sm->state);
2267 } END_FOR_EACH_SM(sm);
2268 } END_FOR_EACH_PTR(cb);
2270 free_string(name);
2273 static void print_return_struct_info(int return_id, char *return_ranges,
2274 struct expression *expr,
2275 struct symbol *sym,
2276 struct return_info_callback *cb)
2278 struct sm_state *sm;
2279 const char *printed_name;
2280 int param;
2282 FOR_EACH_MY_SM(cb->owner, __get_cur_stree(), sm) {
2283 if (sm->sym && sm->sym == sym) {
2284 param = -1;
2285 } else {
2286 param = get_param_num_from_sym(sm->sym);
2287 if (param < 0)
2288 continue;
2291 printed_name = get_param_name(sm);
2292 if (!printed_name)
2293 continue;
2295 cb->callback(return_id, return_ranges, expr, param, printed_name, sm);
2296 } END_FOR_EACH_SM(sm);
2299 static void print_return_info(int return_id, char *return_ranges, struct expression *expr)
2301 struct return_info_callback *cb;
2302 struct expression *tmp;
2303 struct symbol *sym;
2305 if (!option_info && !__inline_fn &&
2306 !local_debug && !option_debug)
2307 return;
2309 tmp = get_fake_variable(expr);
2310 if (tmp)
2311 expr = tmp;
2312 sym = expr_to_sym(expr);
2314 FOR_EACH_PTR(return_callbacks, cb) {
2315 __ignore_param_used++;
2316 print_return_struct_info(return_id, return_ranges, expr, sym, cb);
2317 __ignore_param_used--;
2318 } END_FOR_EACH_PTR(cb);
2321 static void reset_memdb(struct symbol *sym)
2323 mem_sql(NULL, NULL, "delete from caller_info;");
2324 mem_sql(NULL, NULL, "delete from return_states;");
2325 mem_sql(NULL, NULL, "delete from call_implies;");
2326 mem_sql(NULL, NULL, "delete from return_implies;");
2329 static void match_end_func_info(struct symbol *sym)
2331 if (__path_is_null())
2332 return;
2333 call_return_state_hooks(NULL);
2336 static void match_after_func(struct symbol *sym)
2338 if (!__inline_fn)
2339 reset_memdb(sym);
2342 static void init_memdb(void)
2344 char *err = NULL;
2345 int rc;
2346 const char *schema_files[] = {
2347 "db/db.schema",
2348 "db/caller_info.schema",
2349 "db/common_caller_info.schema",
2350 "db/return_states.schema",
2351 "db/function_type_size.schema",
2352 "db/type_size.schema",
2353 "db/function_type_info.schema",
2354 "db/type_info.schema",
2355 "db/call_implies.schema",
2356 "db/return_implies.schema",
2357 "db/function_ptr.schema",
2358 "db/local_values.schema",
2359 "db/function_type_value.schema",
2360 "db/type_value.schema",
2361 "db/function_type.schema",
2362 "db/data_info.schema",
2363 "db/parameter_name.schema",
2364 "db/constraints.schema",
2365 "db/constraints_required.schema",
2366 "db/fn_ptr_data_link.schema",
2367 "db/fn_data_link.schema",
2368 "db/mtag_about.schema",
2369 "db/mtag_info.schema",
2370 "db/mtag_map.schema",
2371 "db/mtag_data.schema",
2372 "db/mtag_alias.schema",
2374 static char buf[4096];
2375 int fd;
2376 int ret;
2377 int i;
2379 rc = sqlite3_open(":memory:", &mem_db);
2380 if (rc != SQLITE_OK) {
2381 sm_ierror("starting In-Memory database.");
2382 return;
2385 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2386 fd = open_schema_file(schema_files[i]);
2387 if (fd < 0)
2388 continue;
2389 ret = read(fd, buf, sizeof(buf));
2390 if (ret < 0) {
2391 sm_ierror("failed to read: %s", schema_files[i]);
2392 continue;
2394 close(fd);
2395 if (ret == sizeof(buf)) {
2396 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2397 schema_files[i], sizeof(buf));
2398 continue;
2400 buf[ret] = '\0';
2401 rc = sqlite3_exec(mem_db, buf, NULL, NULL, &err);
2402 if (rc != SQLITE_OK) {
2403 sm_ierror("SQL error #2: %s", err);
2404 sm_ierror("%s", buf);
2409 static void init_cachedb(void)
2411 char *err = NULL;
2412 int rc;
2413 const char *schema_files[] = {
2414 "db/call_implies.schema",
2415 "db/return_implies.schema",
2416 "db/type_info.schema",
2417 "db/mtag_about.schema",
2418 "db/mtag_data.schema",
2419 "db/mtag_info.schema",
2420 "db/sink_info.schema",
2422 static char buf[4096];
2423 int fd;
2424 int ret;
2425 int i;
2427 rc = sqlite3_open(":memory:", &cache_db);
2428 if (rc != SQLITE_OK) {
2429 sm_ierror("starting In-Memory database.");
2430 return;
2433 for (i = 0; i < ARRAY_SIZE(schema_files); i++) {
2434 fd = open_schema_file(schema_files[i]);
2435 if (fd < 0)
2436 continue;
2437 ret = read(fd, buf, sizeof(buf));
2438 if (ret < 0) {
2439 sm_ierror("failed to read: %s", schema_files[i]);
2440 continue;
2442 close(fd);
2443 if (ret == sizeof(buf)) {
2444 sm_ierror("Schema file too large: %s (limit %zd bytes)",
2445 schema_files[i], sizeof(buf));
2446 continue;
2448 buf[ret] = '\0';
2449 rc = sqlite3_exec(cache_db, buf, NULL, NULL, &err);
2450 if (rc != SQLITE_OK) {
2451 sm_ierror("SQL error #2: %s", err);
2452 sm_ierror("%s", buf);
2457 static int save_cache_data(void *_table, int argc, char **argv, char **azColName)
2459 static char buf[4096];
2460 char tmp[256];
2461 char *p = buf;
2462 char *table = _table;
2463 int i;
2466 p += snprintf(p, 4096 - (p - buf), "insert or ignore into %s values (", table);
2467 for (i = 0; i < argc; i++) {
2468 if (i)
2469 p += snprintf(p, 4096 - (p - buf), ", ");
2470 sqlite3_snprintf(sizeof(tmp), tmp, "%q", escape_newlines(argv[i]));
2471 p += snprintf(p, 4096 - (p - buf), "'%s'", tmp);
2474 p += snprintf(p, 4096 - (p - buf), ");");
2475 if (p - buf > 4096)
2476 return 0;
2478 sm_msg("SQL: %s", buf);
2479 return 0;
2482 static void dump_cache(struct symbol_list *sym_list)
2484 const char *cache_tables[] = {
2485 "type_info", "return_implies", "call_implies", "mtag_data",
2486 "mtag_info", "mtag_about", "sink_info",
2488 char buf[64];
2489 int i;
2491 if (!option_info)
2492 return;
2494 for (i = 0; i < ARRAY_SIZE(cache_tables); i++) {
2495 snprintf(buf, sizeof(buf), "select * from %s;", cache_tables[i]);
2496 cache_sql(&save_cache_data, (char *)cache_tables[i], buf);
2500 void open_smatch_db(char *db_file)
2502 int rc;
2504 if (option_no_db)
2505 return;
2507 use_states = malloc(num_checks + 1);
2508 memset(use_states, 0xff, num_checks + 1);
2510 init_memdb();
2511 init_cachedb();
2513 rc = sqlite3_open_v2(db_file, &smatch_db, SQLITE_OPEN_READONLY, NULL);
2514 if (rc != SQLITE_OK) {
2515 option_no_db = 1;
2516 return;
2518 run_sql(NULL, NULL,
2519 "PRAGMA cache_size = %d;", SQLITE_CACHE_PAGES);
2520 return;
2523 static char *get_next_string(char **str)
2525 static char string[256];
2526 char *start;
2527 char *p = *str;
2528 int len, i, j;
2530 if (*p == '\0')
2531 return NULL;
2532 start = p;
2534 while (*p != '\0' && *p != '\n') {
2535 if (*p == '\\' && *(p + 1) == ' ') {
2536 p += 2;
2537 continue;
2539 if (*p == ' ')
2540 break;
2541 p++;
2544 len = p - start;
2545 if (len >= sizeof(string)) {
2546 memcpy(string, start, sizeof(string));
2547 string[sizeof(string) - 1] = '\0';
2548 sm_ierror("return_fix: '%s' too long", string);
2549 **str = '\0';
2550 return NULL;
2552 memcpy(string, start, len);
2553 string[len] = '\0';
2554 for (i = 0; i < sizeof(string) - 1; i++) {
2555 if (string[i] == '\\' && string[i + 1] == ' ') {
2556 for (j = i; string[j] != '\0'; j++)
2557 string[j] = string[j + 1];
2560 if (*p != '\0')
2561 p++;
2562 *str = p;
2563 return string;
2566 static void register_return_replacements(void)
2568 char *func, *orig, *new;
2569 char filename[256];
2570 char buf[4096];
2571 int fd, ret, i;
2572 char *p;
2574 snprintf(filename, 256, "db/%s.return_fixes", option_project_str);
2575 fd = open_schema_file(filename);
2576 if (fd < 0)
2577 return;
2578 ret = read(fd, buf, sizeof(buf));
2579 close(fd);
2580 if (ret < 0)
2581 return;
2582 if (ret == sizeof(buf)) {
2583 sm_ierror("file too large: %s (limit %zd bytes)",
2584 filename, sizeof(buf));
2585 return;
2587 buf[ret] = '\0';
2589 p = buf;
2590 while (*p) {
2591 get_next_string(&p);
2592 replace_count++;
2594 if (replace_count == 0 || replace_count % 3 != 0) {
2595 replace_count = 0;
2596 return;
2598 replace_table = malloc(replace_count * sizeof(char *));
2600 p = buf;
2601 i = 0;
2602 while (*p) {
2603 func = alloc_string(get_next_string(&p));
2604 orig = alloc_string(get_next_string(&p));
2605 new = alloc_string(get_next_string(&p));
2607 replace_table[i++] = func;
2608 replace_table[i++] = orig;
2609 replace_table[i++] = new;
2613 void register_definition_db_callbacks(int id)
2615 my_id = id;
2617 add_hook(&match_call_info, FUNCTION_CALL_HOOK);
2618 add_hook(&match_call_info_new, FUNCTION_CALL_HOOK);
2619 add_split_return_callback(match_return_info);
2620 add_split_return_callback(print_returned_struct_members);
2621 add_split_return_callback(print_return_info);
2622 add_hook(&call_return_state_hooks, RETURN_HOOK);
2623 add_hook(&match_end_func_info, END_FUNC_HOOK);
2624 add_hook(&match_after_func, AFTER_FUNC_HOOK);
2626 add_hook(&match_data_from_db, FUNC_DEF_HOOK);
2627 add_hook(&match_call_implies, FUNC_DEF_HOOK);
2628 add_hook(&match_return_implies, CALL_HOOK_AFTER_INLINE);
2630 common_funcs = load_strings_from_file(option_project_str, "common_functions");
2631 register_return_replacements();
2633 add_hook(&dump_cache, END_FILE_HOOK);
2636 void register_db_call_marker(int id)
2638 add_hook(&match_call_marker, FUNCTION_CALL_HOOK);
2641 char *get_data_info_name(struct expression *expr)
2643 struct symbol *sym;
2644 char *name;
2645 char buf[256];
2646 char *ret = NULL;
2648 expr = strip_expr(expr);
2649 name = get_member_name(expr);
2650 if (name)
2651 return name;
2652 name = expr_to_var_sym(expr, &sym);
2653 if (!name || !sym)
2654 goto free;
2655 if (!(sym->ctype.modifiers & MOD_TOPLEVEL))
2656 goto free;
2657 if (sym->ctype.modifiers & MOD_STATIC)
2658 snprintf(buf, sizeof(buf), "static %s", name);
2659 else
2660 snprintf(buf, sizeof(buf), "global %s", name);
2661 ret = alloc_sname(buf);
2662 free:
2663 free_string(name);
2664 return ret;