#include <libelf.h>
#include <sys/elf_SPARC.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/procfs.h>

#include "sparc.h"

char sans_nom[] = "sans_nom";
int	affiche_tout = 0;

char *fichier;
char *premiere_fonction = "main";

Elf32_Ehdr	*Elf_Header;
Elf32_Shdr	*TSection;
Elf32_Phdr	*TProgramme;

typedef struct {
	Elf32_Sword	d_tag;
	union {
		Elf32_Word	d_val;
		Elf32_Addr	d_ptr;
	} d_un;
}	Elf32_Dyn;

union sparc_insn
{
	unsigned long int code;
	struct
	{
		unsigned int anop:2;
#define	op	ldst.anop
		unsigned int anrd:5;
#define	rd	ldst.anrd
		unsigned int op3:6;
		unsigned int anrs1:5;
#define	rs1	ldst.anrs1
		unsigned int i:1;
		unsigned int anasi:8;
#define	asi	ldst.anasi
		unsigned int anrs2:5;
#define	rs2	ldst.anrs2
#define	shcnt	rs2
	} ldst;
	struct
	{
		unsigned int anop:2, anrd:5, op3:6, anrs1:5, i:1;
		unsigned int IMM13:13;
#define	imm13	IMM13.IMM13
	} IMM13;
	struct
	{
		unsigned int anop:2;
		unsigned int a:1;
		unsigned int cond:4;
		unsigned int op2:3;
		unsigned int DISP22:22;
#define	disp22	branch.DISP22
#define	imm22	disp22
	} branch;
	struct
	{
		unsigned int anop:2;
		unsigned int adisp30:30;
#define	disp30	call.adisp30
	} call;
};


#define DT_NULL		0
#define DT_NEEDED	1
#define DT_PLTRELSZ	2
#define DT_PLTGOT	3
#define DT_HASH		4
#define DT_STRTAB	5
#define DT_SYMTAB	6
#define DT_RELA		7
#define DT_RELASZ	8
#define DT_RELAENT	9
#define DT_STRSZ	10
#define DT_SYMENT	11
#define DT_INIT		12
#define DT_FINI		13
#define DT_SONAME	14
#define DT_RPATH	15
#define DT_SYMBOLIC	16
#define DT_REL		17
#define DT_RELSZ	18
#define DT_RELENT	19
#define DT_PLTREL	20
#define DT_DEBUG	21
#define DT_TEXTREL	22
#define DT_JMPREL	23
#define DT_FILTER	24

typedef struct {
	char	*nom;
	int	debut;
	int	fin;
	int	deja_decode;
	int	sans_fin;
	int	offset;
}	segment;

segment *carte_memoire = NULL;
int	nb_segment = 0;

void ajouter_segment(char *nom,int debut,int longueur,int sans_fin)
{
	int i,j;

	for (i=0;i<nb_segment;i++)
	{
		if (strcmp(nom,carte_memoire[i].nom) == 0) return;
		if (carte_memoire[i].debut >= debut) break;
	}
	carte_memoire = (segment *)realloc(carte_memoire,(nb_segment+1)*sizeof(segment));
	for (j=nb_segment;j>i;j--)
		carte_memoire[j] = carte_memoire[j-1];
	nb_segment++;

	carte_memoire[i].nom = strdup(nom);
	carte_memoire[i].debut = debut;
	carte_memoire[i].fin = debut + longueur;
	carte_memoire[i].deja_decode = 0;
	carte_memoire[i].sans_fin = sans_fin;
}

segment *segment_suivant()
{
	register int i;

	for (i=0;i<nb_segment;i++)
	{
		if (!carte_memoire[i].deja_decode)
			return &carte_memoire[i];
	}
	return NULL;
}

void afficher_segment()
{
	register int i;

	printf("nombre de segment = %d\n",nb_segment);
	for (i=0;i<nb_segment;i++)
	{
		printf("debut = %x\tfin = %x\tnom = %s\n",
			carte_memoire[i].debut,
			carte_memoire[i].fin,
			carte_memoire[i].nom);
	}
}

int chercher_offset(int addr)
{
	Elf32_Shdr	*section;
	register int i;

	for (i=0;i<Elf_Header->e_shnum;i++)
	{
		section  = (Elf32_Shdr *)&fichier[Elf_Header->e_shoff+i*Elf_Header->e_shentsize];
		if ((section->sh_addr<=addr) && (addr < section->sh_addr + section->sh_size))
			return section->sh_offset+addr-section->sh_addr;
	}
	return 0;
}

char *chercher_entete_section(int addr)
{
	Elf32_Shdr	*section;
	Elf32_Shdr	*autre_section;
	Elf32_Sym	*symbole;
	Elf32_Rela	*reloc;
	static char	nom[50];
	int i,j;
	int longueur = 0,ajouter = 0;

/* pour stocker les meilleurs resultats de la recherche */

	sprintf(nom,"function at 0x%x",addr);
	for (j=0;j<Elf_Header->e_shnum;j++)
	{
		section = (Elf32_Shdr *)&fichier[Elf_Header->e_shoff+j*Elf_Header->e_shentsize];

		if ((section->sh_type == SHT_SYMTAB) || (section->sh_type == SHT_DYNSYM))
		{
			for (i=0;i<section->sh_size/section->sh_entsize;i++)
			{
				symbole = (Elf32_Sym *)&fichier[section->sh_offset+i*section->sh_entsize];
				if (symbole->st_value == addr )
				{
					ajouter = 1;
					if ((symbole->st_name) && (section->sh_link != SHN_UNDEF)
						&& ((section->sh_link < SHN_LORESERVE)
						|| (section->sh_link > SHN_HIRESERVE)))
					{
						if (symbole->st_name < TSection[section->sh_link].sh_size)
						if (fichier[TSection[section->sh_link].sh_offset+symbole->st_name])
							strcpy(nom,&fichier[TSection[section->sh_link].sh_offset+symbole->st_name]);
					}

					if (!longueur)
						longueur = symbole->st_size;

				}
			}
		}
		if (section->sh_type == SHT_RELA)
		{
			for (i=0;i<section->sh_size/section->sh_entsize;i++)
			{
				reloc = (Elf32_Rela *)&fichier[section->sh_offset+i*section->sh_entsize];
				if (reloc->r_offset == addr)
				{
					if ((section->sh_link) && ((section->sh_link < SHN_LORESERVE) 
						|| (section->sh_link > SHN_HIRESERVE)))
					{
						autre_section = &TSection[section->sh_link];
						symbole = (Elf32_Sym *) &fichier[autre_section->sh_offset+
							ELF32_R_SYM(reloc->r_info)*autre_section->sh_entsize];

						if ((symbole->st_name) && (autre_section->sh_link != SHN_UNDEF)
							&& ((autre_section->sh_link < SHN_LORESERVE)
							|| (autre_section->sh_link > SHN_HIRESERVE)))
						{
							if (symbole->st_name < TSection[autre_section->sh_link].sh_size)
							if (fichier[TSection[autre_section->sh_link].sh_offset+symbole->st_name])
								strcpy(nom, &fichier[TSection[autre_section->sh_link].sh_offset+symbole->st_name]);
						}

						if (!longueur)
							longueur = symbole->st_size;
					}
				}
			}
		}
	}

	if (ajouter)
		ajouter_segment(nom,addr,longueur,0);
	return nom;
}

void chercher_main()
{
	Elf32_Shdr	*section;
	Elf32_Sym	*symbole;
	register int i,j;

	for (j=0;j<Elf_Header->e_shnum;j++)
	{
		section = (Elf32_Shdr *)&fichier[Elf_Header->e_shoff+j*Elf_Header->e_shentsize];

		if ((section->sh_type == SHT_SYMTAB) || (section->sh_type == SHT_DYNSYM))
		{
			for (i=0;i<section->sh_size/section->sh_entsize;i++)
			{
				symbole = (Elf32_Sym *)&fichier[section->sh_offset+i*section->sh_entsize];
				if (symbole->st_name)
				{
					if (section->sh_link == SHN_UNDEF)
						continue;
					if ((section->sh_link >= SHN_LORESERVE) && (section->sh_link <= SHN_HIRESERVE))
						continue;
					if (strcmp(premiere_fonction,&fichier[TSection[section->sh_link].sh_offset+symbole->st_name])==0)
					{
						ajouter_segment(premiere_fonction,symbole->st_value,symbole->st_size,1);
						return;
					}
				}
			}
		}
	}
/* on arrive ici si l'on n'a pas trouve la fonction main ou celle
	que l'on cherchait, dans ce cas on cherche le point d'entree du
	programme  */

	printf("pas de fonction main, je cherche alors la premiere fonction executee\n");
	chercher_entete_section(Elf_Header->e_entry);
}

/* Compare opcodes A and B.  */

int compare_opcodes (const void *a,const void *b)
{
 	const struct sparc_opcode *op0 = (const struct sparc_opcode *) a;
 	const struct sparc_opcode *op1 = (const struct sparc_opcode *) b;
	unsigned long int match0 = op0->match, match1 = op1->match;
	unsigned long int lose0 = op0->lose, lose1 = op1->lose;
	unsigned int i;

  /* If a bit is set in both match and lose, there is something
     wrong with the opcode table.  */
  	if (match0 & lose0)
    	{
      		fprintf (stderr, "Internal error:  bad sparc-opcode.h: \"%s\", %#.8lx, %#.8lx\n",
	       		op0->name, match0, lose0);
      		/* op0->lose &= ~op0->match;
      		lose0 = op0->lose; */
    	}

  	if (match1 & lose1)
    	{
      		fprintf (stderr, "Internal error: bad sparc-opcode.h: \"%s\", %#.8lx, %#.8lx\n",
	       		op1->name, match1, lose1);
      		/* op1->lose &= ~op1->match;
      		lose1 = op1->lose; */
    	}

  /* Because the bits that are variable in one opcode are constant in
     another, it is important to order the opcodes in the right order.  */
  	for (i = 0; i < 32; ++i)
    	{
      		unsigned long int x = 1 << i;
      		int x0 = (match0 & x) != 0;
      		int x1 = (match1 & x) != 0;

      		if (x0 != x1)
		{ return x1 - x0; }
    	}

  	for (i = 0; i < 32; ++i)
     	{
      		unsigned long int x = 1 << i;
      		int x0 = (lose0 & x) != 0;
      		int x1 = (lose1 & x) != 0;

      		if (x0 != x1)
		{ return x1 - x0; }
    	}

  /* They are functionally equal.  So as long as the opcode table is
     valid, we can put whichever one first we want, on aesthetic grounds.  */

  /* Our first aesthetic ground is that aliases defer to real insns.  */
  	{
    		int alias_diff = (op0->flags & F_ALIAS) - (op1->flags & F_ALIAS);
    		if (alias_diff != 0)
      /* Put the one that isn't an alias first.  */
     		{ return alias_diff; }
  	}

  /* Except for aliases, two "identical" instructions had
     better have the same opcode.  This is a sanity check on the table.  */
  	i = strcmp (op0->name, op1->name);
  	if (i)
      	if (op0->flags & F_ALIAS) /* If they're both aliases, be arbitrary. */
	{ return i; }
      	else
	  	fprintf (stderr,
		   "Internal error: bad sparc-opcode.h: \"%s\" == \"%s\"\n",
		   op0->name, op1->name);

  /* Fewer arguments are preferred.  */
  	{
   		int length_diff = strlen (op0->args) - strlen (op1->args);
    		if (length_diff != 0)
      /* Put the one with fewer arguments first.  */
    		{ return length_diff; }
  	}

  /* Put 1+i before i+1.  */
  	{
    		char *p0 = (char *) strchr(op0->args, '+');
    		char *p1 = (char *) strchr(op1->args, '+');


    		if (p0 && p1)
      		{
	/* There is a plus in both operands.  Note that a plus
	   sign cannot be the first character in args,
	   so the following [-1]'s are valid.  */
			if (p0[-1] == 'i' && p1[1] == 'i')
	  /* op0 is i+1 and op1 is 1+i, so op1 goes first.  */
				{ return 1; }
			if (p0[1] == 'i' && p1[-1] == 'i')
	  /* op0 is 1+i and op1 is i+1, so op0 goes first.  */
				{ return -1; }
      		}
  	}

  /* They are, as far as we can tell, identical.
     Since qsort may have rearranged the table partially, there is
     no way to tell which one was first in the opcode table as
   	  written, so just say there are equal.  */
	return 0;
}

void instruction_assembleur(int addr,int instr,int prev_instr)
{
	int i;
	union sparc_insn insn;
	union sparc_insn prev_insn;
	register const struct sparc_opcode *opcode;
	int imm_added_to_rs1 = 0;
	int found_plus = 0;
	int is_annulled = 0;
	const char *s;
	int imm;
	static int caca = 0;

/*	a mettre ailleurs */

	if (!caca)
	{
		qsort(sparc_opcodes,NUMOPCODES,sizeof(sparc_opcodes[0]),
			compare_opcodes);
		caca = 1;
	}


/* Sign-extend a value which is N bits long.  */
#define	SEX(value, bits) \
	((((int)(value)) << ((8 * sizeof (int)) - bits))	\
			 >> ((8 * sizeof (int)) - bits) )

	insn.code = instr;
	prev_insn.code = prev_instr;

	for (i=0;i<NUMOPCODES;i++)
	{
		opcode = &sparc_opcodes[i];
		if ((opcode->match & insn.code) == opcode->match
			&& (opcode->lose & insn.code) == 0)
		{
			imm_added_to_rs1 = 0;
			found_plus = 0;
			is_annulled = 0;

			if ((opcode->match == 0x80102000 || opcode->match == 0x80002000)
				&& insn.rs1 == insn.rd)
				imm_added_to_rs1 = 1;
			if (insn.rs1 != insn.rd
				&& strchr(opcode->args,'r') != 0)
				continue;
			printf(opcode->name);
			if (opcode->args[0] != ',')
				printf(" ");
			for (s = opcode->args;*s;++s)
			{
				while (*s == ',')
				{
					printf(",");
					++s;
					switch(*s)
					{
					case 'a':
						printf("a");
						is_annulled = 1;
						++s;
						continue;
					default:
						break;
					}
				}
				printf(" ");
				switch(*s)
				{
				case '+':
					found_plus = 1;
				default:
					printf("%c",*s);
					break;
				case '#':
					printf("0");
					break;

#define	reg(n)	printf("%%%s", reg_names[n])
				case '1':
				case 'r':
					reg (insn.rs1);
					break;

				case '2':
					reg (insn.rs2);
					break;

				case 'd':
					reg (insn.rd);
					break;
#undef	reg

#define	freg(n)		printf("%%%s", freg_names[n])
#define	fregx(n)	printf("%%%s", freg_names[((n) & ~1) | (((n) & 1) << 5)])
				case 'e':
					freg (insn.rs1);
					break;
				case 'v':	/* double/even */
				case 'V':	/* quad/multiple of 4 */
					fregx (insn.rs1);
					break;

				case 'f':
					freg (insn.rs2);
					break;
				case 'B':	/* double/even */
				case 'R':	/* quad/multiple of 4 */
					fregx (insn.rs2);
					break;

				case 'g':
					freg (insn.rd);
					break;
				case 'H':	/* double/even */
				case 'J':	/* quad/multiple of 4 */
					fregx (insn.rd);
					break;
#undef	freg
#undef	fregx

#define	creg(n)	printf("%%c%u", (unsigned int) (n))
				case 'b':
					creg (insn.rs1);
					break;

				case 'c':
					creg (insn.rs2);
					break;

				case 'D':
					creg (insn.rd);
					break;
#undef	creg
				case 'h':
					printf("%%hi(%s)",chercher_entete_section(0xFFFFFFFF & (int) insn.imm22 << 10));
					break;

				case 'i':
					imm = SEX (insn.imm13, 13);

		     			 /* Check to see whether we have a 1+i, and take
						 note of that fact.

						 Note: because of the way we sort the table,
						 we will be matching 1+i rather than i+1,
						 so it is OK to assume that i is after +,
						 not before it.  */
					if (found_plus)
						imm_added_to_rs1 = 1;
		      
					if (imm <= 9)
						printf("%d", imm);
					else
						printf("%#x", imm);
					break;

				case 'M':
					printf("%%asr%d", insn.rs1);
					break;
		    
		  		case 'm':
		    			printf("%%asr%d", insn.rd);
		    			break;
		    
		  		case 'L':
		    		/*	info->target = memaddr + insn.disp30 * 4;
		    			(*info->print_address_func) (info->target, info);
				*/
					printf(chercher_entete_section(addr + insn.disp30 * 4));
		    			break;

		 		 case 'n':
					printf("%#x", (SEX (insn.disp22, 22)));
		    			break;

		  		case 'l':
		    		/*	info->target = memaddr + (SEX (insn.disp22, 22)) * 4;
		    			(*info->print_address_func) (info->target, info);
				*/
					printf(chercher_entete_section(addr + (SEX (insn.disp22, 22)) * 4));
		    			break;

		  		case 'A':
					printf("(%d)", (int) insn.asi);
		    			break;

		  		case 'C':
					printf("%%csr");
		    			break;

		  		case 'F':
					printf("%%fsr");
		    			break;

		  		case 'p':
					printf("%%psr");
		    			break;

		  		case 'q':
					printf("%%fq");
		    			break;

		  		case 'Q':
					printf("%%cq");
		    			break;

		  		case 't':
					printf("%%tbr");
		    			break;

		  		case 'w':
					printf("%%wim");
		    			break;

		  		case 'y':
					printf("%%y");
		    			break;

				}
			}

	  /* If we are adding or or'ing something to rs1, then
	     check to see whether the previous instruction was
	     a sethi to the same register as in the sethi.
	     If so, attempt to print the result of the add or
	     or (in this context add and or do the same thing)
	     and its symbolic value.  */
	  		if (imm_added_to_rs1)
	    		{
		  /* If it is a delayed branch, we need to look at the
		     instruction before the delayed branch.  This handles
		     sequences such as

		     sethi %o1, %hi(_foo), %o1
		     call _printf
		     or %o1, %lo(_foo), %o1
		     */

	/* intraduisible pour l'instant 	  	if (is_delayed_branch (prev_insn))
		    errcode = (*info->read_memory_func)
		      (memaddr - 8, (bfd_byte *)&prev_insn, sizeof (prev_insn),
		       info);
	*/

		/* Is it sethi to the same register?  */
		  		if ((prev_insn.code & 0xc1c00000) == 0x01000000
		      			&& prev_insn.rd == insn.rs1)
				{
			   		printf("\t! ");

	/*	      info->target = 
			(0xFFFFFFFF & (int) prev_insn.imm22 << 10)
			| SEX (insn.imm13, 13);
		      (*info->print_address_func) (info->target, info);
		      info->insn_type = dis_dref;
		      info->data_size = 4;   FIXME!!! 
	*/
					printf(chercher_entete_section((0xFFFFFFFF & (int) prev_insn.imm22 << 10) | SEX (insn.imm13, 13)));
		   		}
			}
			printf("\n");
			return;
		}

	}
}

void desassemble_segment(segment *seg_original)
{
	register signed int *instr;
	segment	seg = *seg_original; /* on prend une copie du segment car ce pointeur
		peut devenir invalide lors d'un ajout dans le tableau carte_memoire,
		mais on garde un pointeur comme parametre, car on a besoin de 
		modifier l'original */
	register int i;
	register int nb_instr = (seg.fin - seg.debut +3)/4;
	int addr,addr_debut;

	printf("%s(%d octets)\n{\n",seg.nom,seg.fin-seg.debut);
	seg_original->deja_decode = 1;
	addr_debut = chercher_offset(seg.debut);
	if (!addr_debut)
	{
		printf("impossible de trouver la section\n");
		return;
	}
	instr = (int *)&fichier[addr_debut];
	for (i=0;i<nb_instr;i++)
	{
		addr = 0;
		if (affiche_tout)
		{
			printf("0x%x : 0x%08x\t",seg.debut+(i<<2),instr[i]);
			instruction_assembleur(seg.debut+(i<<2),instr[i],instr[i-1]);
		}
		if ((instr[i] & 0xc0000000L) == 0x40000000L)
			addr = seg.debut+(i<<2)+((instr[i] | 0xc0000000)<<2);
		if ((instr[i] & 0xfff83fffL) == 0x9fc00000L)
			addr = seg.debut+(i<<2)+((instr[i] & 0xfff83fffL)<<2);
		if (addr)
		{
			if (affiche_tout)
				printf("\t%s(0x%x);\n",chercher_entete_section(addr),addr);
			else
				printf("\t%s();\n",chercher_entete_section(addr));
		}
	}
	printf("}\n\n");
}

int main(int argc,char *argv[])
{
	int fd;
	int taille;
	segment *seg;
	char	*nom_fichier = NULL;
	register int n = 1;

	while(n<argc)
	{
		if (strcmp(argv[n],"-f")==0)
		{
			if (n+1<argc)
			{
				premiere_fonction = argv[n+1];
				n += 2; continue;
			}
		}
		if (strcmp(argv[n],"-v")==0)
		{
			affiche_tout = 1;
			n++; continue;
		}
		if (!nom_fichier)
		{
			nom_fichier = argv[n];
			n++; continue;
		}
		else
		{
			nom_fichier = NULL;
			break;
		}
		n++;
	}

	if (!nom_fichier)
	{
		printf("usage: %s [-f fonction] [-v] fichier_elf\n",argv[0]);
		return -1;
	}

	fd = open(nom_fichier,O_RDONLY);
	if (fd == -1)
	{
		perror(nom_fichier);
		return -1;
	}
	taille = lseek(fd,0,SEEK_END);
	fichier = mmap(0,taille,PROT_READ,MAP_PRIVATE,fd,0);
	if (fichier == MAP_FAILED)
	{
		perror(nom_fichier);
		return -1;
	}
	Elf_Header = (Elf32_Ehdr *)fichier;
	if ((Elf_Header->e_ident[EI_MAG0] == ELFMAG0)
		&& (Elf_Header->e_ident[EI_MAG1] == ELFMAG1)
		&& (Elf_Header->e_ident[EI_MAG2] == ELFMAG2)
		&& (Elf_Header->e_ident[EI_MAG3] == ELFMAG3))
		printf("ce fichier est au format ELF\n");
	else
	{
		printf("ce fichier n'est pas au format ELF\n");
		return -1;
	}
	TSection = (Elf32_Shdr *)&fichier[Elf_Header->e_shoff];
	TProgramme = (Elf32_Phdr *)&fichier[Elf_Header->e_phoff];
	chercher_main();
	while ((seg = segment_suivant()) != NULL)
		desassemble_segment(seg);
	close(fd);
	return 0;
}
