// SPDX-FileCopyrightText: 2014 Ilya V. Matveychikov <i.matveychikov@milabs.ru>
// SPDX-License-Identifier: LGPL-3.0-only

#include <rz_types.h>
#include <rz_lib.h>
#include <rz_asm.h>
#include "asm_private.h"
#include <tms320/c55x_plus/c55plus_arch.h>
#include <tms320/c55x/c55x_analysis.h>
#include <tms320/c54x/c54x.h>
#include <tms320/c64x/c64x.h>

typedef struct tms_cs_context_t {
	void *c64x;
} TmsContext;

static int tms320_disassemble(const RzAsm *a, RzAsmOp *op, const ut8 *buf, int len) {
	TmsContext *ctx = (TmsContext *)a->plugin_data;
	if (a->cpu && !rz_str_casecmp(a->cpu, "c64x")) {
		return tms320_c64x_disassemble(a, op, buf, len, ctx->c64x);
	}
	// C55x / C55x+ / C54x are decoded by the shared decode-IR engine; any other
	// cpu is unknown.
	const C55ArchDesc *desc = NULL;
	if (a->cpu && !rz_str_casecmp(a->cpu, "c55x+")) {
		desc = &c55plus_arch_desc;
	} else if (a->cpu && !rz_str_casecmp(a->cpu, "c55x")) {
		desc = &c55x_arch_desc;
	} else if (a->cpu && !rz_str_casecmp(a->cpu, "c54x")) {
		desc = &c54x_arch_desc;
	} else {
		rz_asm_op_set_asm(op, "unknown asm.cpu");
		return op->size = -1;
	}
	if (desc) {
		C55Insn insn;
		if (c55_decode(desc, buf, len, &insn)) {
			char *s = c55_format(desc, &insn);
			if (s) {
				rz_asm_op_set_asm(op, s);
				free(s);
				return op->size = insn.size;
			}
		}
	}
	rz_asm_op_set_asm(op, "invalid");
	return op->size = 1;
}

static bool tms320_init(void **user) {
	TmsContext *ctx = RZ_NEW0(TmsContext);
	if (!ctx) {
		return false;
	}
	ctx->c64x = tms320_c64x_new();
	*user = ctx;
	return true;
}

static bool tms320_fini(void *user) {
	rz_return_val_if_fail(user, false);
	TmsContext *ctx = (TmsContext *)user;
	tms320_c64x_free(ctx->c64x);
	free(ctx);
	return true;
}

static char *tms320_mnemonics(const RzAsm *a, int id, bool json) {
	TmsContext *ctx = (TmsContext *)a->plugin_data;
	if (!a->cpu || rz_str_casecmp(a->cpu, "c64x")) {
		return NULL;
	}
	return tms320_c64x_mnemonics(a, id, json, ctx->c64x);
}

static char **tms320_cpu_descriptions() {
	static char *cpu_desc[] = {
		"c54x", "Texas Instruments TMS320C54x DSP family",
		"c55x", "Texas Instruments TMS320C55x DSP family",
		"c55x+", "Texas Instruments TMS320C55x+ DSP family",
		"c64x", "Texas Instruments TMS320C64x DSP family",
		NULL
	};
	return cpu_desc;
}

RzAsmPlugin rz_asm_plugin_tms320 = {
	.name = "tms320",
	.arch = "tms320",
	.cpus = "c54x,c55x,c55x+,c64x",
	.desc = "Texas Instruments TMS320 DSP family (c54x,c55x,c55x+,c64x) disassembler",
	.license = "LGPL3",
	.bits = 32,
	.endian = RZ_SYS_ENDIAN_LITTLE | RZ_SYS_ENDIAN_BIG,
	.init = tms320_init,
	.fini = tms320_fini,
	.disassemble = &tms320_disassemble,
	.mnemonics = tms320_mnemonics,
	.get_cpu_desc = tms320_cpu_descriptions,
};
