Esempio n. 1
0
File: util.c Progetto: HarryR/sanos
void dynarray_reset(void *pp, int *n) {
  void **p;
  for (p = *(void***) pp; *n; ++p, --*n) {
    if (*p) tcc_free(*p);
  }
  tcc_free(*(void**) pp);
  *(void**)pp = NULL;
}
Esempio n. 2
0
File: pe.c Progetto: 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;
}
Esempio n. 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;
}
Esempio n. 4
0
File: pe.c Progetto: HarryR/sanos
static int pe_assign_addresses(struct pe_info *pe) {
  int i, k, o, c;
  DWORD addr;
  int *section_order;
  struct section_info *si;
  struct section_info *merged_text;
  struct section_info *merged_data;
  Section *s;

  // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);
  section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
  for (o = k = 0 ; k < sec_last; ++k) {
    for (i = 1; i < pe->s1->nb_sections; ++i) {
      s = pe->s1->sections[i];
      if (k == pe_section_class(s)) {
        s->sh_addr = pe->imagebase;
        section_order[o++] = i;
      }
    }
  }

  pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
  addr = pe->imagebase + 1;

  merged_text = NULL;
  merged_data = NULL;
  for (i = 0; i < o; ++i) {
    k = section_order[i];
    s = pe->s1->sections[k];
    c = pe_section_class(s);
    si = &pe->sec_info[pe->sec_count];

#ifdef PE_MERGE_DATA
    if (c == sec_data && merged_data == NULL) {
      merged_data = si;
    }
    if (c == sec_bss && merged_data != NULL) {
      // Append .bss to .data
      s->sh_addr = addr = ((addr - 1) | 15) + 1;
      addr += s->data_offset;
      merged_data->sh_size = addr - merged_data->sh_addr;
      merged_data->last->next = s;
      merged_data->last = s;
      continue;
    }
#endif

    if (c == sec_text) {
      if (s->unused) continue;
      if (merged_text) {
        merged_text->sh_size = align(merged_text->sh_size, s->sh_addralign);
        s->sh_addr = merged_text->sh_addr + merged_text->sh_size;
        merged_text->sh_size += s->data_offset;
        addr = merged_text->sh_addr + merged_text->sh_size;
        merged_text->last->next = s;
        merged_text->last = s;
        continue;
      } else {
        merged_text = si;
      }
    }

    strcpy(si->name, c == sec_text ? ".text" : s->name);
    si->cls = c;
    si->ord = k;
    si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
    si->sh_flags = s->sh_flags;
    si->first = si->last = s;

    if (c == sec_data && pe->thunk == NULL) {
      pe->thunk = s;
    }

    if (s == pe->thunk) {
      pe_build_imports(pe);
      pe_build_exports(pe);
    }

    if (c == sec_reloc) {
      pe_build_reloc(pe);
    }

    if (s->data_offset) {
      si->sh_size = s->data_offset;
      addr += s->data_offset;
      pe->sec_count++;
    }
  }

  tcc_free(section_order);
  return 0;
}
Esempio n. 5
0
File: pe.c Progetto: HarryR/sanos
static void pe_build_exports(struct pe_info *pe) {
  Elf32_Sym *sym;
  int sym_index, sym_end;
  DWORD rva_base, func_o, name_o, ord_o, str_o;
  struct pe_export_header *hdr;
  int sym_count, n, ord, *sorted, *sp;

  FILE *op;
  char buf[260];
  const char *dllname;
  const char *name;

  rva_base = pe->thunk->sh_addr - pe->imagebase;
  sym_count = 0;
  n = 1;
  sorted = NULL;
  op = NULL;

  sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
  for (sym_index = 1; sym_index < sym_end; ++sym_index) {
    sym = (Elf32_Sym *) symtab_section->data + sym_index;
    name = symtab_section->link->data + sym->st_name;
    // Only export symbols from actually written sections
    if ((sym->st_other & 1) && pe->s1->sections[sym->st_shndx]->sh_addr) {
      dynarray_add((void ***) &sorted, &sym_count, (void *) n);
      dynarray_add((void ***) &sorted, &sym_count, (void *) name);
    }
    ++n;
  }

  if (sym_count == 0) return;
  sym_count /= 2;

  qsort(sorted, sym_count, 2 * sizeof(sorted[0]), sym_cmp);
  pe_align_section(pe->thunk, 16);
  dllname = tcc_basename(pe->filename);

  pe->exp_offs = pe->thunk->data_offset;
  func_o = pe->exp_offs + sizeof(struct pe_export_header);
  name_o = func_o + sym_count * sizeof(DWORD);
  ord_o = name_o + sym_count * sizeof(DWORD);
  str_o = ord_o + sym_count * sizeof(WORD);

  hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
  hdr->Characteristics = 0;
  hdr->Base = 1;
  hdr->NumberOfFunctions = sym_count;
  hdr->NumberOfNames = sym_count;
  hdr->AddressOfFunctions = func_o + rva_base;
  hdr->AddressOfNames = name_o + rva_base;
  hdr->AddressOfNameOrdinals = ord_o + rva_base;
  hdr->Name = str_o + rva_base;
  put_elf_str(pe->thunk, dllname);

  if (pe->def != NULL) {
    // Write exports to .def file
    op = fopen(pe->def, "w");
    if (op == NULL) {
      error_noabort("could not create '%s': %s", pe->def, strerror(errno));
    } else {
      fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
      if (verbose) {
        printf("<- %s (%d symbols)\n", buf, sym_count);
      }
    }
  }

  for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2) {
    sym_index = sp[0]; 
    name = (const char *) sp[1];

    // Insert actual address later in pe_relocate_rva
    put_elf_reloc(symtab_section, pe->thunk, func_o, R_386_RELATIVE, sym_index);
    *(DWORD *)(pe->thunk->data + name_o) = pe->thunk->data_offset + rva_base;
    *(WORD *)(pe->thunk->data + ord_o) = ord;
    put_elf_str(pe->thunk, name);
    func_o += sizeof(DWORD);
    name_o += sizeof(DWORD);
    ord_o += sizeof(WORD);

    if (op) fprintf(op, "%s@%d\n", name, ord);
  }
  pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
  tcc_free(sorted);
  if (op) fclose(op);
}
Esempio n. 6
0
File: pe.c Progetto: HarryR/sanos
static int pe_write(struct pe_info *pe) {
  int i;
  int fd;
  FILE *op;
  FILE *stubfile;
  char *stub;
  int stub_size;
  DWORD file_offset, r;
  Section *s;

  if (pe->stub) {
    stubfile = fopen(pe->stub, "rb");
    if (stubfile == NULL) {
      error_noabort("could not read '%s': %s", pe->stub, strerror(errno));
      return 1;
    }
    fseek(stubfile, 0, SEEK_END);
    stub_size = ftell(stubfile);
    fseek(stubfile, 0, SEEK_SET);
    if (stub_size < sizeof(IMAGE_DOS_HEADER)) {
      error_noabort("invalid stub (%d bytes): %s", stub_size, pe->stub);
      return 1;
    }
    stub = tcc_malloc(stub_size);
    if (fread(stub, 1, stub_size, stubfile) != stub_size) {
      error_noabort("error reading stub '%s': %s", pe->stub, strerror(errno));
      return 1;
    }
    fclose(stubfile);
  } else {
    stub_size = DOSSTUB_SIZE + sizeof(IMAGE_DOS_HEADER);
    stub = tcc_malloc(stub_size);
    memcpy(stub, &pe_doshdr, sizeof(IMAGE_DOS_HEADER));
    memcpy(stub + sizeof(IMAGE_DOS_HEADER), pe_dosstub, DOSSTUB_SIZE);
  }
  ((PIMAGE_DOS_HEADER) stub)->e_lfanew = stub_size;

  fd = open(pe->filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0777);
  if (fd < 0) {
    error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
    return 1;
  }
  op = fdopen(fd, "wb");

  pe->sizeofheaders = 
    pe_file_align(pe,
      stub_size +
      sizeof(DWORD) + 
      sizeof(IMAGE_FILE_HEADER) +
      sizeof(IMAGE_OPTIONAL_HEADER) +
      pe->sec_count * sizeof (IMAGE_SECTION_HEADER));

  file_offset = pe->sizeofheaders;
  pe_fpad(op, file_offset, 0);

  if (verbose == 2) {
    printf("------------------------------------\n  virt   file   size  ord section" "\n");
  }

  for (i = 0; i < pe->sec_count; ++i) {
    struct section_info *si = pe->sec_info + i;
    const char *sh_name = si->name;
    unsigned long addr = si->sh_addr - pe->imagebase;
    unsigned long size = si->sh_size;
    IMAGE_SECTION_HEADER *psh = &si->ish;

    if (verbose == 2) {
      printf("%6lx %6lx %6lx %4d %s\n", addr, file_offset, size, si->ord, sh_name);
    }

    switch (si->cls) {
      case sec_text:
        pe_opthdr.BaseOfCode = addr;
        pe_opthdr.SizeOfCode += size;
        pe_opthdr.AddressOfEntryPoint = ((Elf32_Sym *) symtab_section->data)[pe->start_sym_index].st_value - pe->imagebase;
        break;

      case sec_data:
        pe_opthdr.BaseOfData = addr;
        pe_opthdr.SizeOfInitializedData += size;
        break;

      case sec_bss:
        pe_opthdr.SizeOfUninitializedData += size;
        break;

      case sec_reloc:
        pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
        break;

      case sec_rsrc:
        pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
        break;

      case sec_stab:
        break;
    }

    if (pe->thunk == pe->s1->sections[si->ord]) {
      if (pe->imp_size) {
        pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IMPORT, pe->imp_offs + addr, pe->imp_size);
        pe_set_datadir(IMAGE_DIRECTORY_ENTRY_IAT, pe->iat_offs + addr, pe->iat_size);
      }
      if (pe->exp_size) {
        pe_set_datadir(IMAGE_DIRECTORY_ENTRY_EXPORT, pe->exp_offs + addr, pe->exp_size);
      }
    }

    strcpy((char *) psh->Name, sh_name);
    psh->Characteristics = pe_sec_flags[si->cls];
    psh->VirtualAddress = addr;
    psh->Misc.VirtualSize = size;
    pe_opthdr.SizeOfImage = umax(pe_virtual_align(size + addr), pe_opthdr.SizeOfImage); 

    if (si->sh_size) {
      psh->PointerToRawData = r = file_offset;
      for (s = si->first; s; s = s->next) {
        if (s->sh_type != SHT_NOBITS) {
          file_offset = align(file_offset, s->sh_addralign);
          pe_fpad(op, file_offset, si->cls == sec_text ? 0x90 : 0x00);
          fwrite(s->data, 1, s->data_offset, op);
          file_offset += s->data_offset;
        }
      }
      file_offset = pe_file_align(pe, file_offset);
      psh->SizeOfRawData = file_offset - r;
      pe_fpad(op, file_offset, 0);
    }
  }

  pe_filehdr.TimeDateStamp = time(NULL);
  pe_filehdr.NumberOfSections = pe->sec_count;
  pe_filehdr.Characteristics = do_debug ? 0x0102 : 0x030E;
  pe_opthdr.SizeOfHeaders = pe->sizeofheaders;
  pe_opthdr.ImageBase = pe->imagebase;
  pe_opthdr.FileAlignment = pe->filealign;
  if (pe->type == PE_DLL) {
    pe_filehdr.Characteristics = do_debug ? 0x2102 : 0x230E;
  } else if (pe->type != PE_GUI) {
    pe_opthdr.Subsystem = 3;
  }
  if (!pe->reloc) pe_filehdr.Characteristics |= 1;
  if (pe->s1->noshare) pe_filehdr.Characteristics |= 0x4000;

  fseek(op, 0, SEEK_SET);
  fwrite(stub,  1, stub_size, op);
  fwrite(&pe_ntsig,  1, sizeof pe_ntsig, op);
  fwrite(&pe_filehdr,  1, sizeof pe_filehdr, op);
  fwrite(&pe_opthdr,  1, sizeof pe_opthdr, op);
  for (i = 0; i < pe->sec_count; ++i) {
    fwrite(&pe->sec_info[i].ish, 1, sizeof(IMAGE_SECTION_HEADER), op);
  }
  fclose(op);

  if (verbose == 2) {
    printf("------------------------------------\n");
  }
  if (verbose) {
    printf("<- %s (%lu bytes)\n", pe->filename, file_offset);
  }

  tcc_free(stub);
  return 0;
}
Esempio n. 7
0
char *get_export_names(struct TCCState *tcc_state, int fd)
{
    int l, i, n, n0;
    char *p;

    IMAGE_SECTION_HEADER ish;
    IMAGE_EXPORT_DIRECTORY ied;
    IMAGE_DOS_HEADER dh;
    IMAGE_FILE_HEADER ih;
    DWORD sig, ref, addr, ptr, namep;
#ifdef TCC_TARGET_X86_64
    IMAGE_OPTIONAL_HEADER64 oh;
#else
    IMAGE_OPTIONAL_HEADER32 oh;
#endif
    int pef_hdroffset, opt_hdroffset, sec_hdroffset;

    n = n0 = 0;
    p = NULL;

    if (!read_mem(fd, 0, &dh, sizeof dh))
        goto the_end;
    if (!read_mem(fd, dh.e_lfanew, &sig, sizeof sig))
        goto the_end;
    if (sig != 0x00004550)
        goto the_end;
    pef_hdroffset = dh.e_lfanew + sizeof sig;
    if (!read_mem(fd, pef_hdroffset, &ih, sizeof ih))
        goto the_end;
    if (IMAGE_FILE_MACHINE != ih.Machine)
        goto the_end;
    opt_hdroffset = pef_hdroffset + sizeof ih;
    sec_hdroffset = opt_hdroffset + sizeof oh;
    if (!read_mem(fd, opt_hdroffset, &oh, sizeof oh))
        goto the_end;

    if (IMAGE_DIRECTORY_ENTRY_EXPORT >= oh.NumberOfRvaAndSizes)
        goto the_end;

    addr = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    //printf("addr: %08x\n", addr);
    for (i = 0; i < ih.NumberOfSections; ++i) {
        if (!read_mem(fd, sec_hdroffset + i * sizeof ish, &ish, sizeof ish))
            goto the_end;
        //printf("vaddr: %08x\n", ish.VirtualAddress);
        if (addr >= ish.VirtualAddress && addr < ish.VirtualAddress + ish.SizeOfRawData)
            goto found;
    }
    goto the_end;

found:
    ref = ish.VirtualAddress - ish.PointerToRawData;
    if (!read_mem(fd, addr - ref, &ied, sizeof ied))
        goto the_end;

    namep = ied.AddressOfNames - ref;
    for (i = 0; i < ied.NumberOfNames; ++i) {
        if (!read_mem(fd, namep, &ptr, sizeof ptr))
            goto the_end;
        namep += sizeof ptr;
        for (l = 0;;) {
            if (n+1 >= n0)
				p = tcc_realloc(tcc_state, p, n0 = n0 ? n0 * 2 : 256);
            if (!read_mem(fd, ptr - ref + l++, p + n, 1)) {
				tcc_free(tcc_state, p), p = NULL;
                goto the_end;
            }
            if (p[n++] == 0)
                break;
        }
    }
    if (p)
        p[n] = 0;
the_end:
    return p;
}
Esempio n. 8
0
ST_FUNC int tcc_output_coff(TCCState *s1, FILE *f)
{
    Section *tcc_sect;
    SCNHDR *coff_sec;
    int file_pointer;
    char *Coff_str_table, *pCoff_str_table;
    int CoffTextSectionNo, coff_nb_syms;
    FILHDR file_hdr;		/* FILE HEADER STRUCTURE              */
    Section *stext, *sdata, *sbss;
    int i, NSectionsToOutput = 0;

    Coff_str_table = pCoff_str_table = NULL;

    stext = FindSection(s1, ".text");
    sdata = FindSection(s1, ".data");
    sbss = FindSection(s1, ".bss");

    nb_syms = symtab_section->data_offset / sizeof(Elf32_Sym);
    coff_nb_syms = FindCoffSymbolIndex("XXXXXXXXXX1");

    file_hdr.f_magic = COFF_C67_MAGIC;	/* magic number */
    file_hdr.f_timdat = 0;	/* time & date stamp */
    file_hdr.f_opthdr = sizeof(AOUTHDR);	/* sizeof(optional hdr) */
    file_hdr.f_flags = 0x1143;	/* flags (copied from what code composer does) */
    file_hdr.f_TargetID = 0x99;	/* for C6x = 0x0099 */

    o_filehdr.magic = 0x0108;	/* see magic.h                          */
    o_filehdr.vstamp = 0x0190;	/* version stamp                        */
    o_filehdr.tsize = stext->data_offset;	/* text size in bytes, padded to FW bdry */
    o_filehdr.dsize = sdata->data_offset;	/* initialized data "  "                */
    o_filehdr.bsize = sbss->data_offset;	/* uninitialized data "   "             */
    o_filehdr.entrypt = C67_main_entry_point;	/* entry pt.                          */
    o_filehdr.text_start = stext->sh_addr;	/* base of text used for this file      */
    o_filehdr.data_start = sdata->sh_addr;	/* base of data used for this file      */


    // create all the section headers

    file_pointer = FILHSZ + sizeof(AOUTHDR);

    CoffTextSectionNo = -1;

    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    NSectionsToOutput++;

	    if (CoffTextSectionNo == -1 && tcc_sect == stext)
		CoffTextSectionNo = NSectionsToOutput;	// rem which coff sect number the .text sect is

	    strcpy(coff_sec->s_name, tcc_sect->name);	/* section name */

	    coff_sec->s_paddr = tcc_sect->sh_addr;	/* physical address */
	    coff_sec->s_vaddr = tcc_sect->sh_addr;	/* virtual address */
	    coff_sec->s_size = tcc_sect->data_offset;	/* section size */
	    coff_sec->s_scnptr = 0;	/* file ptr to raw data for section */
	    coff_sec->s_relptr = 0;	/* file ptr to relocation */
	    coff_sec->s_lnnoptr = 0;	/* file ptr to line numbers */
	    coff_sec->s_nreloc = 0;	/* number of relocation entries */
	    coff_sec->s_flags = GetCoffFlags(coff_sec->s_name);	/* flags */
	    coff_sec->s_reserved = 0;	/* reserved byte */
	    coff_sec->s_page = 0;	/* memory page id */

	    file_pointer += sizeof(SCNHDR);
	}
    }

    file_hdr.f_nscns = NSectionsToOutput;	/* number of sections */

    // now loop through and determine file pointer locations
    // for the raw data


    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    // put raw data
	    coff_sec->s_scnptr = file_pointer;	/* file ptr to raw data for section */
	    file_pointer += coff_sec->s_size;
	}
    }

    // now loop through and determine file pointer locations
    // for the relocation data

    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    // put relocations data
	    if (coff_sec->s_nreloc > 0) {
		coff_sec->s_relptr = file_pointer;	/* file ptr to relocation */
		file_pointer += coff_sec->s_nreloc * sizeof(struct reloc);
	    }
	}
    }

    // now loop through and determine file pointer locations
    // for the line number data

    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	coff_sec->s_nlnno = 0;
	coff_sec->s_lnnoptr = 0;

	if (s1->do_debug && tcc_sect == stext) {
	    // count how many line nos data

	    // also find association between source file name and function
	    // so we can sort the symbol table


	    Stab_Sym *sym, *sym_end;
	    char func_name[MAX_FUNC_NAME_LENGTH],
		last_func_name[MAX_FUNC_NAME_LENGTH];
	    unsigned long func_addr, last_pc, pc;
	    const char *incl_files[INCLUDE_STACK_SIZE];
	    int incl_index, len, last_line_num;
	    const char *str, *p;

	    coff_sec->s_lnnoptr = file_pointer;	/* file ptr to linno */


	    func_name[0] = '\0';
	    func_addr = 0;
	    incl_index = 0;
	    last_func_name[0] = '\0';
	    last_pc = 0xffffffff;
	    last_line_num = 1;
	    sym = (Stab_Sym *) stab_section->data + 1;
	    sym_end =
		(Stab_Sym *) (stab_section->data +
			      stab_section->data_offset);

	    nFuncs = 0;
	    while (sym < sym_end) {
		switch (sym->n_type) {
		    /* function start or end */
		case N_FUN:
		    if (sym->n_strx == 0) {
			// end of function

			coff_sec->s_nlnno++;
			file_pointer += LINESZ;

			pc = sym->n_value + func_addr;
			func_name[0] = '\0';
			func_addr = 0;
			EndAddress[nFuncs] = pc;
			FuncEntries[nFuncs] =
			    (file_pointer -
			     LineNoFilePtr[nFuncs]) / LINESZ - 1;
			LastLineNo[nFuncs++] = last_line_num + 1;
		    } else {
			// beginning of function

			LineNoFilePtr[nFuncs] = file_pointer;
			coff_sec->s_nlnno++;
			file_pointer += LINESZ;

			str =
			    (const char *) stabstr_section->data +
			    sym->n_strx;

			p = strchr(str, ':');
			if (!p) {
			    pstrcpy(func_name, sizeof(func_name), str);
			    pstrcpy(Func[nFuncs], sizeof(func_name), str);
			} else {
			    len = p - str;
			    if (len > sizeof(func_name) - 1)
				len = sizeof(func_name) - 1;
			    memcpy(func_name, str, len);
			    memcpy(Func[nFuncs], str, len);
			    func_name[len] = '\0';
			}

			// save the file that it came in so we can sort later
			pstrcpy(AssociatedFile[nFuncs], sizeof(func_name),
				incl_files[incl_index - 1]);

			func_addr = sym->n_value;
		    }
		    break;

		    /* line number info */
		case N_SLINE:
		    pc = sym->n_value + func_addr;

		    last_pc = pc;
		    last_line_num = sym->n_desc;

		    /* XXX: slow! */
		    strcpy(last_func_name, func_name);

		    coff_sec->s_nlnno++;
		    file_pointer += LINESZ;
		    break;
		    /* include files */
		case N_BINCL:
		    str =
			(const char *) stabstr_section->data + sym->n_strx;
		  add_incl:
		    if (incl_index < INCLUDE_STACK_SIZE) {
			incl_files[incl_index++] = str;
		    }
		    break;
		case N_EINCL:
		    if (incl_index > 1)
			incl_index--;
		    break;
		case N_SO:
		    if (sym->n_strx == 0) {
			incl_index = 0;	/* end of translation unit */
		    } else {
			str =
			    (const char *) stabstr_section->data +
			    sym->n_strx;
			/* do not add path */
			len = strlen(str);
			if (len > 0 && str[len - 1] != '/')
			    goto add_incl;
		    }
		    break;
		}
		sym++;
	    }
	}

    }

    file_hdr.f_symptr = file_pointer;	/* file pointer to symtab */

    if (s1->do_debug)
	file_hdr.f_nsyms = coff_nb_syms;	/* number of symtab entries */
    else
	file_hdr.f_nsyms = 0;

    file_pointer += file_hdr.f_nsyms * SYMNMLEN;

    // OK now we are all set to write the file


    fwrite(&file_hdr, FILHSZ, 1, f);
    fwrite(&o_filehdr, sizeof(o_filehdr), 1, f);

    // write section headers
    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    fwrite(coff_sec, sizeof(SCNHDR), 1, f);
	}
    }

    // write raw data
    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    fwrite(tcc_sect->data, tcc_sect->data_offset, 1, f);
	}
    }

    // write relocation data
    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (OutputTheSection(tcc_sect)) {
	    // put relocations data
	    if (coff_sec->s_nreloc > 0) {
		fwrite(tcc_sect->reloc,
		       coff_sec->s_nreloc * sizeof(struct reloc), 1, f);
	    }
	}
    }


    // group the symbols in order of filename, func1, func2, etc
    // finally global symbols

    if (s1->do_debug)
	SortSymbolTable();

    // write line no data

    for (i = 1; i < s1->nb_sections; i++) {
	coff_sec = &section_header[i];
	tcc_sect = s1->sections[i];

	if (s1->do_debug && tcc_sect == stext) {
	    // count how many line nos data


	    Stab_Sym *sym, *sym_end;
	    char func_name[128], last_func_name[128];
	    unsigned long func_addr, last_pc, pc;
	    const char *incl_files[INCLUDE_STACK_SIZE];
	    int incl_index, len, last_line_num;
	    const char *str, *p;

	    LINENO CoffLineNo;

	    func_name[0] = '\0';
	    func_addr = 0;
	    incl_index = 0;
	    last_func_name[0] = '\0';
	    last_pc = 0;
	    last_line_num = 1;
	    sym = (Stab_Sym *) stab_section->data + 1;
	    sym_end =
		(Stab_Sym *) (stab_section->data +
			      stab_section->data_offset);

	    while (sym < sym_end) {
		switch (sym->n_type) {
		    /* function start or end */
		case N_FUN:
		    if (sym->n_strx == 0) {
			// end of function

			CoffLineNo.l_addr.l_paddr = last_pc;
			CoffLineNo.l_lnno = last_line_num + 1;
			fwrite(&CoffLineNo, 6, 1, f);

			pc = sym->n_value + func_addr;
			func_name[0] = '\0';
			func_addr = 0;
		    } else {
			// beginning of function

			str =
			    (const char *) stabstr_section->data +
			    sym->n_strx;


			p = strchr(str, ':');
			if (!p) {
			    pstrcpy(func_name, sizeof(func_name), str);
			} else {
			    len = p - str;
			    if (len > sizeof(func_name) - 1)
				len = sizeof(func_name) - 1;
			    memcpy(func_name, str, len);
			    func_name[len] = '\0';
			}
			func_addr = sym->n_value;
			last_pc = func_addr;
			last_line_num = -1;

			// output a function begin

			CoffLineNo.l_addr.l_symndx =
			    FindCoffSymbolIndex(func_name);
			CoffLineNo.l_lnno = 0;

			fwrite(&CoffLineNo, 6, 1, f);
		    }
		    break;

		    /* line number info */
		case N_SLINE:
		    pc = sym->n_value + func_addr;


		    /* XXX: slow! */
		    strcpy(last_func_name, func_name);

		    // output a line reference

		    CoffLineNo.l_addr.l_paddr = last_pc;

		    if (last_line_num == -1) {
			CoffLineNo.l_lnno = sym->n_desc;
		    } else {
			CoffLineNo.l_lnno = last_line_num + 1;
		    }

		    fwrite(&CoffLineNo, 6, 1, f);

		    last_pc = pc;
		    last_line_num = sym->n_desc;

		    break;

		    /* include files */
		case N_BINCL:
		    str =
			(const char *) stabstr_section->data + sym->n_strx;
		  add_incl2:
		    if (incl_index < INCLUDE_STACK_SIZE) {
			incl_files[incl_index++] = str;
		    }
		    break;
		case N_EINCL:
		    if (incl_index > 1)
			incl_index--;
		    break;
		case N_SO:
		    if (sym->n_strx == 0) {
			incl_index = 0;	/* end of translation unit */
		    } else {
			str =
			    (const char *) stabstr_section->data +
			    sym->n_strx;
			/* do not add path */
			len = strlen(str);
			if (len > 0 && str[len - 1] != '/')
			    goto add_incl2;
		    }
		    break;
		}
		sym++;
	    }
	}
    }

    // write symbol table
    if (s1->do_debug) {
	int k;
	struct syment csym;
	AUXFUNC auxfunc;
	AUXBF auxbf;
	AUXEF auxef;
	int i;
	Elf32_Sym *p;
	const char *name;
	int nstr;
	int n = 0;

	Coff_str_table = (char *) tcc_malloc(MAX_STR_TABLE);
	pCoff_str_table = Coff_str_table;
	nstr = 0;

	p = (Elf32_Sym *) symtab_section->data;


	for (i = 0; i < nb_syms; i++) {

	    name = symtab_section->link->data + p->st_name;

	    for (k = 0; k < 8; k++)
		csym._n._n_name[k] = 0;

	    if (strlen(name) <= 8) {
		strcpy(csym._n._n_name, name);
	    } else {
		if (pCoff_str_table - Coff_str_table + strlen(name) >
		    MAX_STR_TABLE - 1)
		    tcc_error("String table too large");

		csym._n._n_n._n_zeroes = 0;
		csym._n._n_n._n_offset =
		    pCoff_str_table - Coff_str_table + 4;

		strcpy(pCoff_str_table, name);
		pCoff_str_table += strlen(name) + 1;	// skip over null
		nstr++;
	    }

	    if (p->st_info == 4) {
		// put a filename symbol
		csym.n_value = 33;	// ?????
		csym.n_scnum = N_DEBUG;
		csym.n_type = 0;
		csym.n_sclass = C_FILE;
		csym.n_numaux = 0;
		fwrite(&csym, 18, 1, f);
		n++;

	    } else if (p->st_info == 0x12) {
		// find the function data

		for (k = 0; k < nFuncs; k++) {
		    if (strcmp(name, Func[k]) == 0)
			break;
		}

		if (k >= nFuncs) {
		    tcc_error("debug info can't find function: %s", name);
		}
		// put a Function Name

		csym.n_value = p->st_value;	// physical address
		csym.n_scnum = CoffTextSectionNo;
		csym.n_type = MKTYPE(T_INT, DT_FCN, 0, 0, 0, 0, 0);
		csym.n_sclass = C_EXT;
		csym.n_numaux = 1;
		fwrite(&csym, 18, 1, f);

		// now put aux info

		auxfunc.tag = 0;
		auxfunc.size = EndAddress[k] - p->st_value;
		auxfunc.fileptr = LineNoFilePtr[k];
		auxfunc.nextsym = n + 6;	// tktk
		auxfunc.dummy = 0;
		fwrite(&auxfunc, 18, 1, f);

		// put a .bf

		strcpy(csym._n._n_name, ".bf");
		csym.n_value = p->st_value;	// physical address
		csym.n_scnum = CoffTextSectionNo;
		csym.n_type = 0;
		csym.n_sclass = C_FCN;
		csym.n_numaux = 1;
		fwrite(&csym, 18, 1, f);

		// now put aux info

		auxbf.regmask = 0;
		auxbf.lineno = 0;
		auxbf.nentries = FuncEntries[k];
		auxbf.localframe = 0;
		auxbf.nextentry = n + 6;
		auxbf.dummy = 0;
		fwrite(&auxbf, 18, 1, f);

		// put a .ef

		strcpy(csym._n._n_name, ".ef");
		csym.n_value = EndAddress[k];	// physical address  
		csym.n_scnum = CoffTextSectionNo;
		csym.n_type = 0;
		csym.n_sclass = C_FCN;
		csym.n_numaux = 1;
		fwrite(&csym, 18, 1, f);

		// now put aux info

		auxef.dummy = 0;
		auxef.lineno = LastLineNo[k];
		auxef.dummy1 = 0;
		auxef.dummy2 = 0;
		auxef.dummy3 = 0;
		auxef.dummy4 = 0;
		fwrite(&auxef, 18, 1, f);

		n += 6;

	    } else {
		// try an put some type info

		if ((p->st_other & VT_BTYPE) == VT_DOUBLE) {
		    csym.n_type = T_DOUBLE;	// int
		    csym.n_sclass = C_EXT;
		} else if ((p->st_other & VT_BTYPE) == VT_FLOAT) {
		    csym.n_type = T_FLOAT;
		    csym.n_sclass = C_EXT;
		} else if ((p->st_other & VT_BTYPE) == VT_INT) {
		    csym.n_type = T_INT;	// int
		    csym.n_sclass = C_EXT;
		} else if ((p->st_other & VT_BTYPE) == VT_SHORT) {
		    csym.n_type = T_SHORT;
		    csym.n_sclass = C_EXT;
		} else if ((p->st_other & VT_BTYPE) == VT_BYTE) {
		    csym.n_type = T_CHAR;
		    csym.n_sclass = C_EXT;
		} else {
		    csym.n_type = T_INT;	// just mark as a label
		    csym.n_sclass = C_LABEL;
		}


		csym.n_value = p->st_value;
		csym.n_scnum = 2;
		csym.n_numaux = 1;
		fwrite(&csym, 18, 1, f);

		auxfunc.tag = 0;
		auxfunc.size = 0x20;
		auxfunc.fileptr = 0;
		auxfunc.nextsym = 0;
		auxfunc.dummy = 0;
		fwrite(&auxfunc, 18, 1, f);
		n++;
		n++;

	    }

	    p++;
	}
    }

    if (s1->do_debug) {
	// write string table

	// first write the size
	i = pCoff_str_table - Coff_str_table;
	fwrite(&i, 4, 1, f);

	// then write the strings
	fwrite(Coff_str_table, i, 1, f);

	tcc_free(Coff_str_table);
    }

    return 0;
}
Esempio n. 9
0
void SortSymbolTable(void)
{
    int i, j, k, n = 0;
    Elf32_Sym *p, *p2, *NewTable;
    char *name, *name2;

    NewTable = (Elf32_Sym *) tcc_malloc(nb_syms * sizeof(Elf32_Sym));

    p = (Elf32_Sym *) symtab_section->data;


    // find a file symbol, copy it over
    // then scan the whole symbol list and copy any function
    // symbols that match the file association

    for (i = 0; i < nb_syms; i++) {
	if (p->st_info == 4) {
	    name = (char *) symtab_section->link->data + p->st_name;

	    // this is a file symbol, copy it over

	    NewTable[n++] = *p;

	    p2 = (Elf32_Sym *) symtab_section->data;

	    for (j = 0; j < nb_syms; j++) {
		if (p2->st_info == 0x12) {
		    // this is a func symbol

		    name2 =
			(char *) symtab_section->link->data + p2->st_name;

		    // find the function data index

		    for (k = 0; k < nFuncs; k++) {
			if (strcmp(name2, Func[k]) == 0)
			    break;
		    }

		    if (k >= nFuncs) {
                        tcc_error("debug (sort) info can't find function: %s", name2);
		    }

		    if (strcmp(AssociatedFile[k], name) == 0) {
			// yes they match copy it over

			NewTable[n++] = *p2;
		    }
		}
		p2++;
	    }
	}
	p++;
    }

    // now all the filename and func symbols should have been copied over
    // copy all the rest over (all except file and funcs)

    p = (Elf32_Sym *) symtab_section->data;
    for (i = 0; i < nb_syms; i++) {
	if (p->st_info != 4 && p->st_info != 0x12) {
	    NewTable[n++] = *p;
	}
	p++;
    }

    if (n != nb_syms)
	tcc_error("Internal Compiler error, debug info");

    // copy it all back

    p = (Elf32_Sym *) symtab_section->data;
    for (i = 0; i < nb_syms; i++) {
	*p++ = NewTable[i];
    }

    tcc_free(NewTable);
}
Esempio n. 10
0
void clear_code_buf(void) {
  tcc_free(code);
  tcc_free(branch);
  reset_code_buf();
}
Esempio n. 11
0
static int tcc_compile_and_run(char* filename)
{
    console_printf("Compiling script %s...\n", filename);

    void* tcc = NULL;
    TCCState * script_state = NULL;
    void* script_buf = NULL;
    
    tcc = module_load("ML/MODULES/tcc.mo");
    if (!tcc)
    {
        console_printf("Could not load TCC compiler.\n");
        goto err;
    }
    
    script_state = (void*) module_exec(tcc, "tcc_new", 0);
    if (!script_state)
    {
        console_printf("Could not initialize TCC compiler.\n");
        goto err;
    }

    module_exec(tcc, "tcc_set_options", 2, script_state, "-nostdlib");
    module_exec(tcc, "tcc_set_options", 2, script_state, "-Wall");
    module_exec(tcc, "tcc_set_options", 2, script_state, "-IML/scripts");
    module_exec(tcc, "tcc_set_output_type", 2, script_state, TCC_OUTPUT_MEMORY);

    int ret_compile = module_exec(tcc, "tcc_add_file", 2, script_state, filename);
    if (ret_compile < 0)
    {
        console_printf("Compilation error.\n");
        goto err;
    }

    script_load_symbols(tcc, script_state, "ML/modules/5D3_113.sym");

    int size = module_exec(tcc, "tcc_relocate", 2, script_state, NULL);
    if (size <= 0)
    {
        console_printf("Linking error.\n");
        goto err;
    }

    script_buf = (void*) tcc_malloc(size);
    if (!script_buf)
    {
        console_printf("Malloc error.\n");
        goto err;
    }
    
    int ret_link = module_exec(tcc, "tcc_relocate", 2, script_state, script_buf);
    if (ret_link < 0)
    {
        console_printf("Relocate error.\n");
        goto err;
    }
        
    void (*script_main)() = (void*) module_exec(tcc, "tcc_get_symbol", 2, script_state, "main");
    if (!script_main)
    {
        console_printf("Your script should have a main function.\n");
        goto err;
    }

    script_define_param_variables(tcc, script_state);

    module_exec(tcc, "tcc_delete", 1, script_state); script_state = NULL;
    module_unload(tcc); tcc = NULL;

    console_printf("Running script %s...\n", filename);

    /* http://repo.or.cz/w/tinycc.git/commit/6ed6a36a51065060bd5e9bb516b85ff796e05f30 */
    sync_caches();

    script_main();

    tcc_free(script_buf); script_buf = NULL;
    return 0;

err:
    if (script_buf) tcc_free(script_buf);
    if (script_state) module_exec(tcc, "tcc_delete", 1, script_state);
    if (tcc) module_unload(tcc);
    return 1;
}
Esempio n. 12
0
ST_FN int pe_assign_addresses (struct pe_info *pe)
{
    int i, k, o, c;
    DWORD addr;
    int *section_order;
    struct section_info *si;
    Section *s;

    // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC);

    section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int));
    for (o = k = 0 ; k < sec_last; ++k) {
        for (i = 1; i < pe->s1->nb_sections; ++i) {
            s = pe->s1->sections[i];
            if (k == pe_section_class(s)) {
                // printf("%s %d\n", s->name, k);
                s->sh_addr = pe->imagebase;
                section_order[o++] = i;
            }
        }
    }

    pe->sec_info = tcc_mallocz(o * sizeof (struct section_info));
    addr = pe->imagebase + 1;

    for (i = 0; i < o; ++i)
    {
        k = section_order[i];
        s = pe->s1->sections[k];
        c = pe_section_class(s);
        si = &pe->sec_info[pe->sec_count];

#ifdef PE_MERGE_DATA
        if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) {
            /* append .bss to .data */
            s->sh_addr = addr = ((addr-1) | 15) + 1;
            addr += s->data_offset;
            si[-1].sh_size = addr - si[-1].sh_addr;
            continue;
        }
#endif
        strcpy(si->name, s->name);
        si->cls = c;
        si->ord = k;
        si->sh_addr = s->sh_addr = addr = pe_virtual_align(addr);
        si->sh_flags = s->sh_flags;

        if (c == sec_data && NULL == pe->thunk)
            pe->thunk = s;

        if (s == pe->thunk) {
            pe_build_imports(pe);
            pe_build_exports(pe);
        }

        if (c == sec_reloc)
            pe_build_reloc (pe);

        if (s->data_offset)
        {
            if (s->sh_type != SHT_NOBITS) {
                si->data = s->data;
                si->data_size = s->data_offset;
            }

            addr += s->data_offset;
            si->sh_size = s->data_offset;
            ++pe->sec_count;
        }
        // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name);
    }

#if 0
    for (i = 1; i < pe->s1->nb_sections; ++i) {
        Section *s = pe->s1->sections[i];
        int type = s->sh_type;
        int flags = s->sh_flags;
        printf("section %-16s %-10s %5x %s,%s,%s\n",
            s->name,
            type == SHT_PROGBITS ? "progbits" :
            type == SHT_NOBITS ? "nobits" :
            type == SHT_SYMTAB ? "symtab" :
            type == SHT_STRTAB ? "strtab" :
            type == SHT_REL ? "rel" : "???",
            s->data_offset,
            flags & SHF_ALLOC ? "alloc" : "",
            flags & SHF_WRITE ? "write" : "",
            flags & SHF_EXECINSTR ? "exec" : ""
            );
    }
    pe->s1->verbose = 2;
#endif

    tcc_free(section_order);
    return 0;
}
Esempio n. 13
0
ST_FN void pe_build_exports(struct pe_info *pe)
{
    Elf32_Sym *sym;
    int sym_index, sym_end;
    DWORD rva_base, func_o, name_o, ord_o, str_o;
    struct pe_export_header *hdr;
    int sym_count, n, ord, *sorted, *sp;

    FILE *op;
    char buf[MAX_PATH];
    const char *dllname;
    const char *name;

    rva_base = pe->thunk->sh_addr - pe->imagebase;
    sym_count = 0, n = 1, sorted = NULL, op = NULL;

    sym_end = symtab_section->data_offset / sizeof(Elf32_Sym);
    for (sym_index = 1; sym_index < sym_end; ++sym_index) {
        sym = (Elf32_Sym*)symtab_section->data + sym_index;
        name = symtab_section->link->data + sym->st_name;
        if ((sym->st_other & 1)
            /* export only symbols from actually written sections */
            && pe->s1->sections[sym->st_shndx]->sh_addr) {
            dynarray_add((void***)&sorted, &sym_count, (void*)n);
            dynarray_add((void***)&sorted, &sym_count, (void*)name);
        }
        ++n;
#if 0
        if (sym->st_other & 1)
            printf("export: %s\n", name);
        if (sym->st_other & 2)
            printf("stdcall: %s\n", name);
#endif
    }

    if (0 == sym_count)
        return;
    sym_count /= 2;

    qsort (sorted, sym_count, 2 * sizeof sorted[0], sym_cmp);
    pe_align_section(pe->thunk, 16);
    dllname = tcc_basename(pe->filename);

    pe->exp_offs = pe->thunk->data_offset;
    func_o = pe->exp_offs + sizeof(struct pe_export_header);
    name_o = func_o + sym_count * sizeof (DWORD);
    ord_o = name_o + sym_count * sizeof (DWORD);
    str_o = ord_o + sym_count * sizeof(WORD);

    hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs);
    hdr->Characteristics        = 0;
    hdr->Base                   = 1;
    hdr->NumberOfFunctions      = sym_count;
    hdr->NumberOfNames          = sym_count;
    hdr->AddressOfFunctions     = func_o + rva_base;
    hdr->AddressOfNames         = name_o + rva_base;
    hdr->AddressOfNameOrdinals  = ord_o + rva_base;
    hdr->Name                   = str_o + rva_base;
    put_elf_str(pe->thunk, dllname);

#if 1
    /* automatically write exports to <output-filename>.def */
    strcpy(buf, pe->filename);
    strcpy(tcc_fileextension(buf), ".def");
    op = fopen(buf, "w");
    if (NULL == op) {
        error_noabort("could not create '%s': %s", buf, strerror(errno));
    } else {
        fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
        if (pe->s1->verbose)
            printf("<- %s (%d symbols)\n", buf, sym_count);
    }
#endif

    for (sp = sorted, ord = 0; ord < sym_count; ++ord, sp += 2)
    {
        sym_index = sp[0], name = (const char *)sp[1];
        /* insert actual address later in pe_relocate_rva */
        put_elf_reloc(symtab_section, pe->thunk,
            func_o, R_386_RELATIVE, sym_index);
        *(DWORD*)(pe->thunk->data + name_o)
            = pe->thunk->data_offset + rva_base;
        *(WORD*)(pe->thunk->data + ord_o)
            = ord;
        put_elf_str(pe->thunk, name);
        func_o += sizeof (DWORD);
        name_o += sizeof (DWORD);
        ord_o += sizeof (WORD);

        if (op)
            fprintf(op, "%s\n", name);
    }
    pe->exp_size = pe->thunk->data_offset - pe->exp_offs;
    tcc_free(sorted);
}
Esempio n. 14
0
File: util.c Progetto: HarryR/sanos
void cstr_free(CString *cstr) {
  tcc_free(cstr->data_allocated);
  cstr_new(cstr);
}