Beispiel #1
0
Datei: pe.c Projekt: HarryR/sanos
int pe_output_file(TCCState *s1, const char *filename) {
  int ret;
  struct pe_info pe;
  int i;

  memset(&pe, 0, sizeof pe);
  pe.filename = filename;
  pe.s1 = s1;

  // Generate relocation information by default for Sanos.
  if (s1->imagebase == 0xFFFFFFFF) {
    pe.reloc = new_section(s1, ".reloc", SHT_PROGBITS, 0);
    pe.imagebase = pe.type == PE_DLL ? 0x10000000 : 0x00400000;
  } else {
    pe.imagebase = s1->imagebase;
  }

  pe_add_runtime_ex(s1, &pe);
  relocate_common_syms(); // Assign bss adresses
  tcc_add_linker_symbols(s1);

  if (!s1->nofll) pe_eliminate_unused_sections(&pe);

  ret = pe_check_symbols(&pe);
  if (ret != 0) return ret;
  
  pe_assign_addresses(&pe);
  relocate_syms(s1, 0);

  for (i = 1; i < s1->nb_sections; ++i) {
    Section *s = s1->sections[i];
    if (s->reloc) {
      relocate_section(s1, s);
      pe_relocate_rva(&pe, s);
    }
  }

  if (s1->nb_errors) {
    ret = 1;
  } else {
    ret = pe_write(&pe);
  }

  if (s1->mapfile) pe_print_sections(s1, s1->mapfile);

  tcc_free(pe.sec_info);
  return ret;
}
Dwfl_Error
internal_function
__libdwfl_relocate (Dwfl_Module *mod, Elf *debugfile, bool debug)
{
  assert (mod->e_type == ET_REL);

  GElf_Ehdr ehdr_mem;
  const GElf_Ehdr *ehdr = gelf_getehdr (debugfile, &ehdr_mem);
  if (ehdr == NULL)
    return DWFL_E_LIBELF;

  size_t d_shstrndx;
  if (elf_getshdrstrndx (debugfile, &d_shstrndx) < 0)
    return DWFL_E_LIBELF;

  RELOC_SYMTAB_CACHE (reloc_symtab);

  /* Look at each section in the debuginfo file, and process the
     relocation sections for debugging sections.  */
  Dwfl_Error result = DWFL_E_NOERROR;
  Elf_Scn *scn = NULL;
  while (result == DWFL_E_NOERROR
	 && (scn = elf_nextscn (debugfile, scn)) != NULL)
    {
      GElf_Shdr shdr_mem;
      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

      if ((shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
	  && shdr->sh_size != 0)
	{
	  /* It's a relocation section.  */

	  Elf_Scn *tscn = elf_getscn (debugfile, shdr->sh_info);
	  if (unlikely (tscn == NULL))
	    result = DWFL_E_LIBELF;
	  else
	    result = relocate_section (mod, debugfile, ehdr, d_shstrndx,
				       &reloc_symtab, scn, shdr, tscn,
				       debug, !debug);
	}
    }

  return result;
}
Beispiel #3
0
PUB_FN int pe_output_file(TCCState * s1, const char *filename)
{
    int ret;
    struct pe_info pe;
    int i;

    memset(&pe, 0, sizeof pe);
    pe.filename = filename;
    pe.s1 = s1;

    pe_add_runtime_ex(s1, &pe);
    relocate_common_syms(); /* assign bss adresses */
    tcc_add_linker_symbols(s1);

    ret = pe_check_symbols(&pe);
    if (0 == ret) {
        if (PE_DLL == pe.type) {
            pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0);
            pe.imagebase = 0x10000000;
        } else {
            pe.imagebase = 0x00400000;
        }
        pe_assign_addresses(&pe);
        relocate_syms(s1, 0);
        for (i = 1; i < s1->nb_sections; ++i) {
            Section *s = s1->sections[i];
            if (s->reloc) {
                relocate_section(s1, s);
                pe_relocate_rva(&pe, s);
            }
        }
        if (s1->nb_errors)
            ret = 1;
        else
            ret = pe_write(&pe);
        tcc_free(pe.sec_info);
    }

#ifdef PE_PRINT_SECTIONS
    pe_print_sections(s1, "tcc.log");
#endif
    return ret;
}
Beispiel #4
0
static int
load_relocatable(char *img, struct module *m)
{
	Elf32_Ehdr *ehdr;
	Elf32_Shdr *shdr;
	paddr_t sect_base, bss_base;
	int i;

	strshndx = 0;
	ehdr = (Elf32_Ehdr *)img;
	shdr = (Elf32_Shdr *)((paddr_t)ehdr + ehdr->e_shoff);
	bss_base = 0;
	m->phys = load_base;
	ELFDBG(("phys addr=%lx\n", load_base));

	/* Copy sections */
	for (i = 0; i < (int)ehdr->e_shnum; i++, shdr++) {
		sect_addr[i] = 0;
		if (shdr->sh_type == SHT_PROGBITS) {

			ELFDBG(("sh_addr=%x\n", shdr->sh_addr));
			ELFDBG(("sh_size=%x\n", shdr->sh_size));
			ELFDBG(("sh_offset=%x\n", shdr->sh_offset));
			ELFDBG(("sh_flags=%x\n", shdr->sh_flags));

			switch (shdr->sh_flags & SHF_VALID) {
			case (SHF_ALLOC | SHF_EXECINSTR):
				/* Text */
				m->text = (vaddr_t)ptokv(load_base);
				break;
			case (SHF_ALLOC | SHF_WRITE):
				/* Data */
				if (m->data == 0) {
					m->data = (vaddr_t)ptokv(load_base +
								 shdr->sh_addr);
				}
				break;
			case SHF_ALLOC:
				/* rodata */
				/* Note: rodata is treated as text. */
				break;
			default:
				continue;
			}
			sect_base = load_base + shdr->sh_addr;
			memcpy((char *)sect_base, img + shdr->sh_offset,
			       (size_t)shdr->sh_size);
			ELFDBG(("load: offset=%lx size=%x\n",
				 sect_base, (int)shdr->sh_size));

			sect_addr[i] = (char *)sect_base;
		} else if (shdr->sh_type == SHT_NOBITS) {
			/* BSS */
			m->bsssz = (size_t)shdr->sh_size;
			sect_base = load_base + shdr->sh_addr;
			bss_base = sect_base;

			/* Zero fill BSS */
			memset((char *)bss_base, 0, (size_t)shdr->sh_size);

			sect_addr[i] = (char *)sect_base;
		} else if (shdr->sh_type == SHT_SYMTAB) {
			/* Symbol table */
			ELFDBG(("load: symtab index=%d link=%d\n",
				i, shdr->sh_link));
			sect_addr[i] = img + shdr->sh_offset;
			if (strshndx != 0)
				panic("Multiple symtab found!");
			strshndx = (int)shdr->sh_link;
		} else if (shdr->sh_type == SHT_STRTAB) {
			/* String table */
			sect_addr[i] = img + shdr->sh_offset;
			ELFDBG(("load: strtab index=%d addr=%x\n",
				i, sect_addr[i]));
		}
	}
	m->textsz = (size_t)(m->data - m->text);
	m->datasz = (size_t)((char *)ptokv(bss_base) - m->data);

	load_base = bss_base + m->bsssz;
	load_base = round_page(load_base);

	ELFDBG(("module load_base=%lx text=%lx\n", load_base, m->text));
	m->size = (size_t)(load_base - kvtop(m->text));
	m->entry = (vaddr_t)ptokv(ehdr->e_entry + m->phys);
	ELFDBG(("module size=%x entry=%lx\n", m->size, m->entry));

	/* Process relocation */
	shdr = (Elf32_Shdr *)((paddr_t)ehdr + ehdr->e_shoff);
	for (i = 0; i < (int)ehdr->e_shnum; i++, shdr++) {
		if (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA) {
			if (relocate_section(img, shdr) != 0) {
				DPRINTF(("Relocation error: module=%s\n", m->name));
				return -1;
			}
		}
	}
	return 0;
}
Beispiel #5
0
/*---------------------------------------------------------------------------*/
int
elfloader_load(char* filename, char* fltfile)
{
  struct elf32_ehdr ehdr;
  struct elf32_shdr shdr;
  struct elf32_shdr strtable;
  unsigned int strs;
  unsigned int shdrptr;
  unsigned int nameptr;
  char name[12];
  
  int i;
  unsigned short shdrnum, shdrsize;

  int ret;

  /* Ensure that we have a correct and compatible ELF header. */
  ret = b_seek_read( 0, (char *)&ehdr, sizeof(ehdr));
  if (ret != sizeof(ehdr)) return ELFFLT_INPUT_ERROR;

  if(memcmp(ehdr.e_ident, elf_magic_header, sizeof(elf_magic_header)) != 0) {
    	PRINTERR(stderr, "ELF header problems\n");
    return ELFFLT_BAD_ELF_HEADER;
  }

  if ( FLAG_VERBOSE )
    	printf ("Grab section header\n");

  // Grab the section header.
  shdrptr = ehdr.e_shoff;
  ret = b_seek_read( shdrptr, (char *)&shdr, sizeof(shdr));
  if (ret != sizeof(shdr)) return ELFFLT_INPUT_ERROR;
  
  shdrsize = ehdr.e_shentsize;
  shdrnum = ehdr.e_shnum;

  if ( FLAG_VERBOSE )
    	printf ("Grab string table section\n");

  // Grab the string table section for the names of the sections. 
  ret = b_seek_read( ehdr.e_shoff + shdrsize * ehdr.e_shstrndx,
                             (char *)&strtable, sizeof(strtable));
  if (ret != sizeof(strtable)) return ELFFLT_INPUT_ERROR;
  strs = strtable.sh_offset;

  /* Parse segments headers to releavant_section entries.
		.text = actual code from the ELF file
		.data = initialized data
		.rodata = contains read-only data
		.bss = segment holds the size of the unitialized data segment
		.rel.text, .rel.data = relocation information for the contents 
					of the ".text" and ".data" segments, respectively.
		.symtab = symbol table for this file
		.strtab = points to the actual string names used by the symbol table.
  */


  // Zero size is indicator of unitialized (not found) section
  text.size = text.relasize = data.size = data.relasize =
    rodata.size = rodata.relasize = symtabsize = strtabsize = 0;

  bss.number = data.number = rodata.number = text.number = -1;
                
  shdrptr = ehdr.e_shoff;
  for(i = 0; i < shdrnum; ++i) {

    ret = b_seek_read( shdrptr, (char *)&shdr, sizeof(shdr));
	DEBUGPRINTF("==shdrptr=0x%x, sizeof=%d; size=0x%x\n",shdrptr,sizeof(shdr),shdrsize );
    if (ret != sizeof(shdr)) { PRINTERR(stderr, "input error at %s:%d :loaded%d",__FILE__,__LINE__,ret);return ELFFLT_INPUT_ERROR;}
    
    /* The name of the section is contained in the strings table. */
    nameptr = strs + shdr.sh_name;
	DEBUGPRINTF("==nameptr=%x(%x+%x), size=%d\n",nameptr,strs,shdr.sh_name,sizeof(name) );
    ret = b_seek_read( nameptr, name, sizeof(name));
    if (ret != sizeof(name)) {PRINTERR(stderr, "input error at %s:%d",__FILE__,__LINE__); return ELFFLT_INPUT_ERROR;}

	DEBUGPRINTF("==shdrptr=0x%x, sizeof=%d; size=0x%x\n",shdrptr,sizeof(shdr),shdrsize );
	if ( FLAG_DUMP_SECTIONS )
		printf ("Section #%d: %-15s [section header 0x%x, offset=0x%x, size %d, vma=0x%x]\n",i,name,shdrptr,
													shdr.sh_offset,shdr.sh_size, shdr.sh_addr);

    if(strncmp(name, ".text", 5) == 0) {
      text.number = i;
      text.offset = shdr.sh_offset;
      text.size = shdr.sh_size;
	  text.base_addr = shdr.sh_addr;
    } else if(strncmp(name, ".rel.text", 9) == 0) {
      text.relaoff = shdr.sh_offset;
      text.relasize = shdr.sh_size;
    } else if(strncmp(name, ".data", 5) == 0) {
      data.number = i;
      data.offset = shdr.sh_offset;
      data.size = shdr.sh_size;
	  data.base_addr = shdr.sh_addr;
    } else if(strncmp(name, ".rodata", 7) == 0) {
      rodata.number = i;
      rodata.offset = shdr.sh_offset;
      rodata.size = shdr.sh_size;
	  rodata.base_addr = shdr.sh_addr;
    } else if(strncmp(name, ".rel.rodata", 11) == 0) {
      rodata.relaoff = shdr.sh_offset;
      rodata.relasize = shdr.sh_size;
    } else if(strncmp(name, ".rel.data", 9) == 0) {
      data.relaoff = shdr.sh_offset;
      data.relasize = shdr.sh_size;
    } else if(strncmp(name, ".rela.", 6) == 0) {
      PRINTERR(stderr,"RELA relocs are not supported.");
      return ELFFLT_INPUT_ERROR;
    } else if(strncmp(name, ".symtab", 7) == 0) {
      symtaboff = shdr.sh_offset;
      symtabsize = shdr.sh_size;
    } else if(strncmp(name, ".strtab", 7) == 0) {
      strtaboff = shdr.sh_offset;
      strtabsize = shdr.sh_size;
    } else if(strncmp(name, ".bss", 4) == 0) {
      bss.size = shdr.sh_size;
      bss.number = i;
      bss.offset = 0;
    }

    shdrptr += shdrsize;
  }

  if(symtabsize == 0) {
    PRINTERR(stderr,"No symbol table found.");
    return ELFFLT_NO_SYMTAB;
  }
  if(strtabsize == 0) {
    PRINTERR(stderr,"No strings table found.");
    return ELFFLT_NO_STRTAB;
  }
  if(text.size == 0) {
    PRINTERR(stderr, "No .text segment found.");
  	return ELFFLT_NO_TEXT;
  }

  if ( (text.relasize + rodata.relasize+ data.relasize) <=0 ) {
      PRINTERR(stderr,"Found no reloc sections. Please link with -r -d options.\n");
      return ELFFLT_UNHANDLED_RELOC;
  }

  if (bss.size) {
    bss.address = (char *)malloc(bss.size);
    if (!bss.address) return ELFFLT_OUTPUT_ERROR;
  }
  if (data.size) {
    data.address = (char *)malloc(data.size);
    if (!data.address) return ELFFLT_OUTPUT_ERROR;
  }
  if (text.size) {
    text.address = (char *)malloc(text.size);
    if (!text.address) return ELFFLT_OUTPUT_ERROR;
  }
  if (rodata.size) {
    rodata.address =  (char *)malloc(rodata.size);
    if (!rodata.address) return ELFFLT_OUTPUT_ERROR;
  }

  rodata.name=".rodata";
  bss.name=".bss";
  text.name=".text";
  data.name=".data";



  b_seek_read(text.offset, text.address, text.size);
  b_seek_read(data.offset, data.address, data.size);
  b_seek_read(rodata.offset, rodata.address, rodata.size);

  if ( FLAG_DUMP_SOURCE ) {
    dump_section( text.name, (unsigned char *)text.address, text.size );
    dump_section( data.name, (unsigned char *)data.address, data.size );
    dump_section( rodata.name, (unsigned char *)rodata.address, rodata.size );
  }

  if ( FLAG_DUMP_SYMBOLS ) {
    dump_symtable();
  }

  if ( FLAG_DUMP_SYMBOLS || FLAG_DUMP_SOURCE || FLAG_VERBOSE )
	 printf("\n\n");

  if ( FLAG_VERBOSE )
   	 printf ("Prepare flat\n");

  int div0hack_size = sizeof(div0_arm);

  int flatmainsize = sizeof(struct flat_hdr)+text.size+div0hack_size+data.size+rodata.size+bss.size;  
  int flatrelocsize = text.relasize+rodata.relasize+data.relasize;


  // Take to account aligning to int32 each section  
  flatmainsize += align4(text.size) + align4(data.size) + align4(rodata.size) + align4(bss.size);
  
  flat_buf=malloc( flatmainsize+flatrelocsize );      
  if ( !flat_buf) { PRINTERR(stderr, "fail to malloc flat buf\n"); return ELFFLT_OUTPUT_ERROR;}
  memset(flat_buf, 0, flatmainsize+flatrelocsize);
  
  //import is subset of full reloc list, so same count is enough
  // but apply multiplier to take into account difference between sizeofs
  flat_import_buf=malloc( flatrelocsize* sizeof(import_record_t)/sizeof(reloc_record_t) );      		
  if ( !flat_import_buf) { PRINTERR(stderr, "fail to malloc flat import buf\n"); return ELFFLT_OUTPUT_ERROR;}
  memset(flat_import_buf, 0, flatrelocsize);

  // Fill flat with sections aligned to int32

  flat = (struct flat_hdr*) flat_buf;

  if ( FLAG_VERBOSE )
      printf(">>elf2flt: load segments\n");
  int offset=sizeof(struct flat_hdr);
  text.flat_offset = offset;
  memcpy( flat_buf+offset, text.address, text.size );
  DEBUGPRINTF("load .txt to %x (%x->%x)\n",offset,text.size,text.size+align4(text.size));
  offset+=text.size+div0hack_size+align4(text.size);


  rodata.flat_offset = offset;
  DEBUGPRINTF("load .rodata to %x (%x->%x)\n",offset,rodata.size,rodata.size+align4(rodata.size));
  memcpy( flat_buf+offset, rodata.address, rodata.size );
  offset+=rodata.size+align4(rodata.size);

  data.flat_offset = offset;
  DEBUGPRINTF("load .data to %x (%x->%x)\n",offset,data.size,data.size+align4(data.size));
  memcpy( flat_buf+offset, data.address, data.size );
  offset+=data.size+align4(data.size);

  bss.flat_offset = offset;
  DEBUGPRINTF(".bss to %x (%x->%x)\n",offset,bss.size,bss.size+align4(bss.size));
  DEBUGPRINTF("result=%x\n",  flatmainsize);

  // Initialize flat headers
  memcpy(flat->magic, FLAT_MAGIC_NUMBER, sizeof(flat->magic));       // Set magic (CHDK_FLAT)
  flat->rev = FLAT_VERSION;
  flat->entry = text.flat_offset;
  flat->data_start = rodata.flat_offset;
  flat->bss_start = bss.flat_offset;  
  flat->reloc_start = flatmainsize;
  flat_reloc_count = 0;

  flat->import_start = 0;
  flat_import_count = 0;
  
  flat_reloc = (reloc_record_t*)(flat_buf+flatmainsize);  
  flat_reloc_cur = flat_reloc;

  flat_import_cur = flat_import_buf;

  // _div0_arm hack
  add_div0_arm();

  flag_unsafe_sym = 0;

  // Do relocations
  ret = relocate_section( &text);
  if(ret != ELFFLT_OK)
      return ret;  
  ret = relocate_section( &rodata);
  if(ret != ELFFLT_OK)
      return ret;
  ret = relocate_section( &data);
  if(ret != ELFFLT_OK)
      return ret;

  if ( flag_unsafe_sym )
      return ELFFLT_UNSAFE_SYMBOL;

  flat->import_start = flat->reloc_start+flat_reloc_count*sizeof(reloc_record_t);

  // Init offsets to the entry symbols
                  
  if ( FLAG_VERBOSE )
   	  printf(">>elf2flt: lookup entry symbols\n");

  flat->_module_info_offset = find_symbol_inflat("_module_info", &data );
  if ( flat->_module_info_offset <=0 ) {
    PRINTERR(stderr, "No or invalid section of _module_info. This symbol should be initialized as ModuleInfo structure.\n");
    return ELFFLT_NO_MODULEINFO;
  }

  struct ModuleInfo* _module_info = (struct ModuleInfo*) (flat_buf + flat->_module_info_offset);
  if ( _module_info->magicnum != MODULEINFO_V1_MAGICNUM ) 
  {
    PRINTERR(stderr, "Wrong _module_info->magicnum value. Please check correct filling of this structure\n");
    return ELFFLT_NO_MODULEINFO;
  }
  if ( _module_info->sizeof_struct != sizeof(struct ModuleInfo) ) 
  {
    PRINTERR(stderr, "Wrong _module_info->sizeof_struct value. Please check correct filling of this structure\n");
    return ELFFLT_NO_MODULEINFO;
  }

  // Group import relocations
  //  Input = array of offset/index pairs - one for each address to be relocated to a core CHDK symbol
  //  Output = list of entries of the form:
  //        Index, Offset1 | (N<<24), Offset2, ..., OffsetN
  //  where each offset is a reference to the same core CHDK symbol
  uint32_t *new_import_buf = malloc(flat_import_count*3*sizeof(uint32_t));
  uint32_t new_import_cnt = 0;
  int process = 1;
  while (process)
  {
      process = 0;
      for (i=0; i<flat_import_count; i++)
      {
          if (flat_import_buf[i].offs != 0)
          {
              process = 1;
              int cnt = 0;
              uint32_t idx = flat_import_buf[i].importidx;
              new_import_buf[new_import_cnt++] = idx;
              int pcnt = new_import_cnt;
              int j;
              for (j=0; j<flat_import_count; j++)
              {
                  if (flat_import_buf[j].importidx == idx)
                  {
                      new_import_buf[new_import_cnt++] = flat_import_buf[j].offs;
                      flat_import_buf[j].offs = 0;
                      cnt++;
                  }
              }
              new_import_buf[pcnt] = (cnt << 24) | new_import_buf[pcnt];
          }
      }
  }

  flat->file_size = flat->import_start+new_import_cnt*sizeof(uint32_t);

  if ( FLAG_DUMP_FLT_HEADERS ) {
	printf("\nFLT Headers:\n");
	printf("->entry        0x%x (size %d)\n", flat->entry, flat->data_start - flat->entry );
	printf("->data_start   0x%x (size %d)\n", flat->data_start,  flat->bss_start - flat->data_start );
	printf("->bss_start    0x%x (size %d)\n", flat->bss_start,   flat->reloc_start - flat->bss_start );
	printf("->reloc_start  0x%x (size %d)\n", flat->reloc_start, flat_reloc_count*sizeof(reloc_record_t) );
	printf("->import_start 0x%x (size %d %d)\n", flat->import_start, flat->file_size-flat->import_start, flat_import_count*sizeof(import_record_t) );
    printf("\n");

	printf("\nModule info:\n");
	printf("->Module Name: %s\n", get_flat_string(_module_info->moduleName) );
	printf("->Module Ver: %d.%d\n", _module_info->module_version.major, _module_info->module_version.minor );

	char* branches_str[] = {"any branch","CHDK", "CHDK_DE", "CHDK_SDM", "PRIVATEBUILD"};
	int branch = (_module_info->chdk_required_branch>REQUIRE_CHDK_PRIVATEBUILD) ? 
						REQUIRE_CHDK_PRIVATEBUILD : _module_info->chdk_required_branch;
	printf("->Require: %s-build%d. ", branches_str[branch], _module_info->chdk_required_ver );
	if ( _module_info->chdk_required_platfid == 0 )
	  	printf("Any platform.\n");
	else
	  	printf(" Platform #%d only.\n", _module_info->chdk_required_platfid );
	printf("->Description: %s\n", get_flat_string(_module_info->description) );
	print_offs("->lib                 = ", (int)_module_info->lib,"\n");
	//print_offs("->_module_loader()    = ", (int)_module_info->loader,"\n");
	//print_offs("->_module_unloader()  = ", (int)_module_info->unloader,"\n");
	//print_offs("->_module_can_unload()= ", (int)_module_info->can_unload,"\n");
	//print_offs("->_module_exit_alt()  = ", (int)_module_info->exit_alt,"\n");
  }

  if ( FLAG_DUMP_FLAT ) {
    dump_section( "FLT_header", (unsigned char*)flat_buf, sizeof(struct flat_hdr) );
    dump_section( "FLT_text", (unsigned char*)flat_buf+flat->entry, flat->data_start-flat->entry );
    dump_section( "FLT_data", (unsigned char*)flat_buf+flat->data_start, flat->bss_start-flat->data_start);
    dump_section( "FLT_bss",  (unsigned char*)flat_buf+flat->bss_start, flat->reloc_start-flat->bss_start );

    printf("\nDump relocations 0x%x (size=%d):\n",flat->reloc_start,flat_reloc_count*sizeof(reloc_record_t));
    for( i = 0; i< flat_reloc_count; i++)
    {
        print_offs("Offs: ",*(int*)(flat_buf+flat->reloc_start+i*sizeof(reloc_record_t)), "\n");
    }

    printf("\nDump imports 0x%x (size=%d):\n",flat->import_start,new_import_cnt*sizeof(uint32_t));
    for (i = 0; i< new_import_cnt;)
    {
        uint32_t idx = new_import_buf[i++];
        int cnt = new_import_buf[i] >> 24;
        int j;
        for (j=0; j<cnt; j++)
        {
            uint32_t offs = new_import_buf[i++] & 0x00FFFFFF;
            print_offs((j==0)?"Offs: ":"      ",offs,"");
		    int addend = *(uint32_t*)(flat_buf+offs);
		    printf(" = sym_%08x[%s]+0x%x\n",idx,get_import_symbol(idx),addend);
        }
    }
  }

  int filesize = flat->file_size;

  printf("\n\nOutput file %s (size=%d bytes)\n",fltfile,filesize);

  int output_fd = open(fltfile,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,0777);
  i = write(output_fd, flat_buf, flat->import_start);
  i = write(output_fd, new_import_buf, new_import_cnt*sizeof(uint32_t));
  close(output_fd);

  return ELFFLT_OK;
}
static Dwfl_Error
relocate_section (Dwfl_Module *mod, Elf *relocated, const GElf_Ehdr *ehdr,
		  size_t shstrndx, struct reloc_symtab_cache *reloc_symtab,
		  Elf_Scn *scn, GElf_Shdr *shdr,
		  Elf_Scn *tscn, bool debugscn, bool partial)
{
  /* First, fetch the name of the section these relocations apply to.  */
  GElf_Shdr tshdr_mem;
  GElf_Shdr *tshdr = gelf_getshdr (tscn, &tshdr_mem);
  const char *tname = elf_strptr (relocated, shstrndx, tshdr->sh_name);
  if (tname == NULL)
    return DWFL_E_LIBELF;

  if (unlikely (tshdr->sh_type == SHT_NOBITS) || unlikely (tshdr->sh_size == 0))
    /* No contents to relocate.  */
    return DWFL_E_NOERROR;

  if (debugscn && ! ebl_debugscn_p (mod->ebl, tname))
    /* This relocation section is not for a debugging section.
       Nothing to do here.  */
    return DWFL_E_NOERROR;

  /* Fetch the section data that needs the relocations applied.  */
  Elf_Data *tdata = elf_rawdata (tscn, NULL);
  if (tdata == NULL)
    return DWFL_E_LIBELF;

  /* Apply one relocation.  Returns true for any invalid data.  */
  Dwfl_Error relocate (GElf_Addr offset, const GElf_Sxword *addend,
		       int rtype, int symndx)
  {
    /* First see if this is a reloc we can handle.
       If we are skipping it, don't bother resolving the symbol.  */

    if (unlikely (rtype == 0))
      /* In some odd situations, the linker can leave R_*_NONE relocs
	 behind.  This is probably bogus ld -r behavior, but the only
	 cases it's known to appear in are harmless: DWARF data
	 referring to addresses in a section that has been discarded.
	 So we just pretend it's OK without further relocation.  */
      return DWFL_E_NOERROR;

    Elf_Type type = ebl_reloc_simple_type (mod->ebl, rtype);
    if (unlikely (type == ELF_T_NUM))
      return DWFL_E_BADRELTYPE;

    /* First, resolve the symbol to an absolute value.  */
    GElf_Addr value;

    if (symndx == STN_UNDEF)
      /* When strip removes a section symbol referring to a
	 section moved into the debuginfo file, it replaces
	 that symbol index in relocs with STN_UNDEF.  We
	 don't actually need the symbol, because those relocs
	 are always references relative to the nonallocated
	 debugging sections, which start at zero.  */
      value = 0;
    else
      {
	GElf_Sym sym;
	GElf_Word shndx;
	Dwfl_Error error = relocate_getsym (mod, relocated, reloc_symtab,
					    symndx, &sym, &shndx);
	if (unlikely (error != DWFL_E_NOERROR))
	  return error;

	if (shndx == SHN_UNDEF || shndx == SHN_COMMON)
	  {
	    /* Maybe we can figure it out anyway.  */
	    error = resolve_symbol (mod, reloc_symtab, &sym, shndx);
	    if (error != DWFL_E_NOERROR
		&& !(error == DWFL_E_RELUNDEF && shndx == SHN_COMMON))
	      return error;
	  }

	value = sym.st_value;
      }

    /* These are the types we can relocate.  */
#define TYPES		DO_TYPE (BYTE, Byte); DO_TYPE (HALF, Half);	\
    DO_TYPE (WORD, Word); DO_TYPE (SWORD, Sword);			\
    DO_TYPE (XWORD, Xword); DO_TYPE (SXWORD, Sxword)
    size_t size;
    switch (type)
      {
#define DO_TYPE(NAME, Name)			\
	case ELF_T_##NAME:			\
	  size = sizeof (GElf_##Name);		\
	break
	TYPES;
#undef DO_TYPE
      default:
	return DWFL_E_BADRELTYPE;
      }

    if (offset + size > tdata->d_size)
      return DWFL_E_BADRELOFF;

#define DO_TYPE(NAME, Name) GElf_##Name Name;
    union { TYPES; } tmpbuf;
#undef DO_TYPE
    Elf_Data tmpdata =
      {
	.d_type = type,
	.d_buf = &tmpbuf,
	.d_size = size,
	.d_version = EV_CURRENT,
      };
    Elf_Data rdata =
      {
	.d_type = type,
	.d_buf = tdata->d_buf + offset,
	.d_size = size,
	.d_version = EV_CURRENT,
      };

    /* XXX check for overflow? */
    if (addend)
      {
	/* For the addend form, we have the value already.  */
	value += *addend;
	switch (type)
	  {
#define DO_TYPE(NAME, Name)			\
	    case ELF_T_##NAME:			\
	      tmpbuf.Name = value;		\
	    break
	    TYPES;
#undef DO_TYPE
	  default:
	    abort ();
	  }
      }
    else
      {
	/* Extract the original value and apply the reloc.  */
	Elf_Data *d = gelf_xlatetom (relocated, &tmpdata, &rdata,
				     ehdr->e_ident[EI_DATA]);
	if (d == NULL)
	  return DWFL_E_LIBELF;
	assert (d == &tmpdata);
	switch (type)
	  {
#define DO_TYPE(NAME, Name)				\
	    case ELF_T_##NAME:				\
	      tmpbuf.Name += (GElf_##Name) value;	\
	    break
	    TYPES;
#undef DO_TYPE
	  default:
	    abort ();
	  }
      }

    /* Now convert the relocated datum back to the target
       format.  This will write into rdata.d_buf, which
       points into the raw section data being relocated.  */
    Elf_Data *s = gelf_xlatetof (relocated, &rdata, &tmpdata,
				 ehdr->e_ident[EI_DATA]);
    if (s == NULL)
      return DWFL_E_LIBELF;
    assert (s == &rdata);

    /* We have applied this relocation!  */
    return DWFL_E_NOERROR;
  }

  /* Fetch the relocation section and apply each reloc in it.  */
  Elf_Data *reldata = elf_getdata (scn, NULL);
  if (reldata == NULL)
    return DWFL_E_LIBELF;

  Dwfl_Error result = DWFL_E_NOERROR;
  bool first_badreltype = true;
  inline void check_badreltype (void)
  {
    if (first_badreltype)
      {
	first_badreltype = false;
	if (ebl_get_elfmachine (mod->ebl) == EM_NONE)
	  /* This might be because ebl_openbackend failed to find
	     any libebl_CPU.so library.  Diagnose that clearly.  */
	  result = DWFL_E_UNKNOWN_MACHINE;
      }
  }

  size_t nrels = shdr->sh_size / shdr->sh_entsize;
  size_t complete = 0;
  if (shdr->sh_type == SHT_REL)
    for (size_t relidx = 0; !result && relidx < nrels; ++relidx)
      {
	GElf_Rel rel_mem, *r = gelf_getrel (reldata, relidx, &rel_mem);
	if (r == NULL)
	  return DWFL_E_LIBELF;
	result = relocate (r->r_offset, NULL,
			   GELF_R_TYPE (r->r_info),
			   GELF_R_SYM (r->r_info));
	check_badreltype ();
	if (partial)
	  switch (result)
	    {
	    case DWFL_E_NOERROR:
	      /* We applied the relocation.  Elide it.  */
	      memset (&rel_mem, 0, sizeof rel_mem);
	      gelf_update_rel (reldata, relidx, &rel_mem);
	      ++complete;
	      break;
	    case DWFL_E_BADRELTYPE:
	    case DWFL_E_RELUNDEF:
	      /* We couldn't handle this relocation.  Skip it.  */
	      result = DWFL_E_NOERROR;
	      break;
	    default:
	      break;
	    }
      }
  else
    for (size_t relidx = 0; !result && relidx < nrels; ++relidx)
      {
	GElf_Rela rela_mem, *r = gelf_getrela (reldata, relidx,
					       &rela_mem);
	if (r == NULL)
	  return DWFL_E_LIBELF;
	result = relocate (r->r_offset, &r->r_addend,
			   GELF_R_TYPE (r->r_info),
			   GELF_R_SYM (r->r_info));
	check_badreltype ();
	if (partial)
	  switch (result)
	    {
	    case DWFL_E_NOERROR:
	      /* We applied the relocation.  Elide it.  */
	      memset (&rela_mem, 0, sizeof rela_mem);
	      gelf_update_rela (reldata, relidx, &rela_mem);
	      ++complete;
	      break;
	    case DWFL_E_BADRELTYPE:
	    case DWFL_E_RELUNDEF:
	      /* We couldn't handle this relocation.  Skip it.  */
	      result = DWFL_E_NOERROR;
	      break;
	    default:
	      break;
	    }
      }

  if (likely (result == DWFL_E_NOERROR))
    {
      if (!partial || complete == nrels)
	/* Mark this relocation section as being empty now that we have
	   done its work.  This affects unstrip -R, so e.g. it emits an
	   empty .rela.debug_info along with a .debug_info that has
	   already been fully relocated.  */
	nrels = 0;
      else if (complete != 0)
	{
	  /* We handled some of the relocations but not all.
	     We've zeroed out the ones we processed.
	     Now remove them from the section.  */

	  size_t next = 0;
	  if (shdr->sh_type == SHT_REL)
	    for (size_t relidx = 0; relidx < nrels; ++relidx)
	      {
		GElf_Rel rel_mem;
		GElf_Rel *r = gelf_getrel (reldata, relidx, &rel_mem);
		if (r->r_info != 0 || r->r_offset != 0)
		  {
		    if (next != relidx)
		      gelf_update_rel (reldata, next, r);
		    ++next;
		  }
	      }
	  else
	    for (size_t relidx = 0; relidx < nrels; ++relidx)
	      {
		GElf_Rela rela_mem;
		GElf_Rela *r = gelf_getrela (reldata, relidx, &rela_mem);
		if (r->r_info != 0 || r->r_offset != 0 || r->r_addend != 0)
		  {
		    if (next != relidx)
		      gelf_update_rela (reldata, next, r);
		    ++next;
		  }
	      }
	  nrels = next;
	}

      shdr->sh_size = reldata->d_size = nrels * shdr->sh_entsize;
      gelf_update_shdr (scn, shdr);
    }

  return result;
}

Dwfl_Error
internal_function
__libdwfl_relocate (Dwfl_Module *mod, Elf *debugfile, bool debug)
{
  assert (mod->e_type == ET_REL);

  GElf_Ehdr ehdr_mem;
  const GElf_Ehdr *ehdr = gelf_getehdr (debugfile, &ehdr_mem);
  if (ehdr == NULL)
    return DWFL_E_LIBELF;

  size_t d_shstrndx;
  if (elf_getshdrstrndx (debugfile, &d_shstrndx) < 0)
    return DWFL_E_LIBELF;

  RELOC_SYMTAB_CACHE (reloc_symtab);

  /* Look at each section in the debuginfo file, and process the
     relocation sections for debugging sections.  */
  Dwfl_Error result = DWFL_E_NOERROR;
  Elf_Scn *scn = NULL;
  while (result == DWFL_E_NOERROR
	 && (scn = elf_nextscn (debugfile, scn)) != NULL)
    {
      GElf_Shdr shdr_mem;
      GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);

      if ((shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
	  && shdr->sh_size != 0)
	{
	  /* It's a relocation section.  */

	  Elf_Scn *tscn = elf_getscn (debugfile, shdr->sh_info);
	  if (unlikely (tscn == NULL))
	    result = DWFL_E_LIBELF;
	  else
	    result = relocate_section (mod, debugfile, ehdr, d_shstrndx,
				       &reloc_symtab, scn, shdr, tscn,
				       debug, !debug);
	}
    }

  return result;
}
Beispiel #7
0
/*---------------------------------------------------------------------------*/
int
elfloader_load(int fd)
{
  struct elf32_ehdr ehdr;
  struct elf32_shdr shdr;
  struct elf32_shdr strtable;
  unsigned int strs;
  unsigned int shdrptr;
  unsigned int nameptr;
  char name[12];
  
  int i;
  unsigned short shdrnum, shdrsize;

  unsigned char using_relas = -1;
  unsigned short textoff = 0, textsize, textrelaoff = 0, textrelasize;
  unsigned short dataoff = 0, datasize, datarelaoff = 0, datarelasize;
  unsigned short rodataoff = 0, rodatasize, rodatarelaoff = 0, rodatarelasize;
  unsigned short symtaboff = 0, symtabsize;
  unsigned short strtaboff = 0, strtabsize;
  unsigned short bsssize = 0;

  struct process **process;
  int ret;

  elfloader_unknown[0] = 0;

  /* The ELF header is located at the start of the buffer. */
  seek_read(fd, 0, (char *)&ehdr, sizeof(ehdr));

  /*  print_chars(ehdr.e_ident, sizeof(elf_magic_header));
      print_chars(elf_magic_header, sizeof(elf_magic_header));*/
  /* Make sure that we have a correct and compatible ELF header. */
  if(memcmp(ehdr.e_ident, elf_magic_header, sizeof(elf_magic_header)) != 0) {
    PRINTF("ELF header problems\n");
    return ELFLOADER_BAD_ELF_HEADER;
  }

  /* Grab the section header. */
  shdrptr = ehdr.e_shoff;
  seek_read(fd, shdrptr, (char *)&shdr, sizeof(shdr));
  
  /* Get the size and number of entries of the section header. */
  shdrsize = ehdr.e_shentsize;
  shdrnum = ehdr.e_shnum;

  PRINTF("Section header: size %d num %d\n", shdrsize, shdrnum);
  
  /* The string table section: holds the names of the sections. */
  seek_read(fd, ehdr.e_shoff + shdrsize * ehdr.e_shstrndx,
	    (char *)&strtable, sizeof(strtable));

  /* Get a pointer to the actual table of strings. This table holds
     the names of the sections, not the names of other symbols in the
     file (these are in the sybtam section). */
  strs = strtable.sh_offset;

  PRINTF("Strtable offset %d\n", strs);
  
  /* Go through all sections and pick out the relevant ones. The
     ".text" segment holds the actual code from the ELF file, the
     ".data" segment contains initialized data, the ".bss" segment
     holds the size of the unitialized data segment. The ".rel[a].text"
     and ".rel[a].data" segments contains relocation information for the
     contents of the ".text" and ".data" segments, respectively. The
     ".symtab" segment contains the symbol table for this file. The
     ".strtab" segment points to the actual string names used by the
     symbol table.

     In addition to grabbing pointers to the relevant sections, we
     also save the section number for resolving addresses in the
     relocator code.
  */


  /* Initialize the segment sizes to zero so that we can check if
     their sections was found in the file or not. */
  textsize = textrelasize = datasize = datarelasize =
    rodatasize = rodatarelasize = symtabsize = strtabsize = 0;

  bss.number = data.number = rodata.number = text.number = -1;
		
  shdrptr = ehdr.e_shoff;
  for(i = 0; i < shdrnum; ++i) {

    seek_read(fd, shdrptr, (char *)&shdr, sizeof(shdr));
    
    /* The name of the section is contained in the strings table. */
    nameptr = strs + shdr.sh_name;
    seek_read(fd, nameptr, name, sizeof(name));
    PRINTF("Section shdrptr 0x%x, %d + %d type %d\n",
	   shdrptr,
	   strs, shdr.sh_name,
	   (int)shdr.sh_type);
    /* Match the name of the section with a predefined set of names
       (.text, .data, .bss, .rela.text, .rela.data, .symtab, and
       .strtab). */
    /* added support for .rodata, .rel.text and .rel.data). */

    if(shdr.sh_type == SHT_SYMTAB/*strncmp(name, ".symtab", 7) == 0*/) {
      PRINTF("symtab\n");
      symtaboff = shdr.sh_offset;
      symtabsize = shdr.sh_size;
    } else if(shdr.sh_type == SHT_STRTAB/*strncmp(name, ".strtab", 7) == 0*/) {
      PRINTF("strtab\n");
      strtaboff = shdr.sh_offset;
      strtabsize = shdr.sh_size;
    } else if(strncmp(name, ".text", 5) == 0) {
      textoff = shdr.sh_offset;
      textsize = shdr.sh_size;
      text.number = i;
      text.offset = textoff;
    } else if(strncmp(name, ".rel.text", 9) == 0) {
      using_relas = 0;
      textrelaoff = shdr.sh_offset;
      textrelasize = shdr.sh_size;
    } else if(strncmp(name, ".rela.text", 10) == 0) {
      using_relas = 1;
      textrelaoff = shdr.sh_offset;
      textrelasize = shdr.sh_size;
    } else if(strncmp(name, ".data", 5) == 0) {
      dataoff = shdr.sh_offset;
      datasize = shdr.sh_size;
      data.number = i;
      data.offset = dataoff;
    } else if(strncmp(name, ".rodata", 7) == 0) {
      /* read-only data handled the same way as regular text section */
      rodataoff = shdr.sh_offset;
      rodatasize = shdr.sh_size;
      rodata.number = i;
      rodata.offset = rodataoff;
    } else if(strncmp(name, ".rel.rodata", 11) == 0) {
      /* using elf32_rel instead of rela */
      using_relas = 0;
      rodatarelaoff = shdr.sh_offset;
      rodatarelasize = shdr.sh_size;
    } else if(strncmp(name, ".rela.rodata", 12) == 0) {
      using_relas = 1;
      rodatarelaoff = shdr.sh_offset;
      rodatarelasize = shdr.sh_size;
    } else if(strncmp(name, ".rel.data", 9) == 0) {
      /* using elf32_rel instead of rela */
      using_relas = 0;
      datarelaoff = shdr.sh_offset;
      datarelasize = shdr.sh_size;
    } else if(strncmp(name, ".rela.data", 10) == 0) {
      using_relas = 1;
      datarelaoff = shdr.sh_offset;
      datarelasize = shdr.sh_size;
    } else if(strncmp(name, ".bss", 4) == 0) {
      bsssize = shdr.sh_size;
      bss.number = i;
      bss.offset = 0;
    }

    /* Move on to the next section header. */
    shdrptr += shdrsize;
  }

  if(symtabsize == 0) {
    return ELFLOADER_NO_SYMTAB;
  }
  if(strtabsize == 0) {
    return ELFLOADER_NO_STRTAB;
  }
  if(textsize == 0) {
    return ELFLOADER_NO_TEXT;
  }

  PRINTF("before allocate ram\n");
  bss.address = (char *)elfloader_arch_allocate_ram(bsssize + datasize);
  data.address = (char *)bss.address + bsssize;
  PRINTF("before allocate rom\n");
  text.address = (char *)elfloader_arch_allocate_rom(textsize + rodatasize);
  rodata.address = (char *)text.address + textsize;
  

  PRINTF("bss base address: bss.address = 0x%08x\n", bss.address);
  PRINTF("data base address: data.address = 0x%08x\n", data.address);
  PRINTF("text base address: text.address = 0x%08x\n", text.address);
  PRINTF("rodata base address: rodata.address = 0x%08x\n", rodata.address);


  /* If we have text segment relocations, we process them. */
  PRINTF("elfloader: relocate text\n");
  if(textrelasize > 0) {
	    ret = relocate_section(fd,
			   textrelaoff, textrelasize,
			   textoff,
			   text.address,
			   strs,
			   strtaboff,
			   symtaboff, symtabsize, using_relas);
    if(ret != ELFLOADER_OK) {
      return ret;
    }
  }

  /* If we have any rodata segment relocations, we process them too. */
  PRINTF("elfloader: relocate rodata\n");
  if(rodatarelasize > 0) {
    ret = relocate_section(fd,
			   rodatarelaoff, rodatarelasize,
			   rodataoff,
			   rodata.address,
			   strs,
			   strtaboff,
			   symtaboff, symtabsize, using_relas);
    if(ret != ELFLOADER_OK) {
      PRINTF("elfloader: data failed\n");
      return ret;
    }
  }

  /* If we have any data segment relocations, we process them too. */
  PRINTF("elfloader: relocate data\n");
  if(datarelasize > 0) {
    ret = relocate_section(fd,
			   datarelaoff, datarelasize,
			   dataoff,
			   data.address,
			   strs,
			   strtaboff,
			   symtaboff, symtabsize, using_relas);
    if(ret != ELFLOADER_OK) {
      PRINTF("elfloader: data failed\n");
      return ret;
    }
  }

  /* Write text and rodata segment into flash and data segment into RAM. */
  elfloader_arch_write_rom(fd, textoff, textsize, text.address);
  elfloader_arch_write_rom(fd, rodataoff, rodatasize, rodata.address);
  
  memset(bss.address, 0, bsssize);
  seek_read(fd, dataoff, data.address, datasize);

  PRINTF("elfloader: autostart search\n");
  process = (struct process **) find_local_symbol(fd, "autostart_processes", symtaboff, symtabsize, strtaboff);
  if(process != NULL) {
    PRINTF("elfloader: autostart found\n");
    elfloader_autostart_processes = process;
    return ELFLOADER_OK;
  } else {
    PRINTF("elfloader: no autostart\n");
    process = (struct process **) find_program_processes(fd, symtaboff, symtabsize, strtaboff);
    if(process != NULL) {
      PRINTF("elfloader: FOUND PRG\n");
    }
    return ELFLOADER_NO_STARTPOINT;
  }
}