/*
 * Copyright 2023 Linaro Ltd.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/copyleft/gpl.txt
 */

#include "smatch.h"
#include "smatch_slist.h"
#include "smatch_extra.h"

static int my_id;

static unsigned long warned;

static void match_return(struct expression *expr)
{
	static int eprobe_id;
	struct symbol *type;
	struct sm_state *sm;
	sval_t sval;

	if (warned)
		return;

	if (!expr || !get_value(expr, &sval))
		return;
	if (sval.value == -517)
		return;

	type = cur_func_return_type();
	if (type != &int_ctype)
		return;

	if (eprobe_id == 0)
		eprobe_id = id_from_name("register_kernel_EPROBE_DEFER");

	FOR_EACH_MY_SM(eprobe_id, __get_cur_stree(), sm) {
		if (strncmp(sm->name, "__fake_", 7) == 0)
			continue;
		if (!is_EPROBE_DEFER_name_sym(sm->name, sm->sym))
			continue;
		if (sm->state != &undefined) {
			sm_warning("why not propogate EPROBE_DEFER from '%s'", sm->name);
			warned = 1;
		}
		return;
	} END_FOR_EACH_SM(sm);
}

void check_propagate_EPROBE_DEFER2(int id)
{
	my_id = id;

	if (option_project != PROJ_KERNEL)
		return;

	add_function_data(&warned);
	add_hook(&match_return, RETURN_HOOK);
}