Exemplo n.º 1
0
spv_result_t spvBinaryToText(const spv_const_context context,
                             const uint32_t* code, const size_t wordCount,
                             const uint32_t options, spv_text* pText,
                             spv_diagnostic* pDiagnostic) {
  // Invalid arguments return error codes, but don't necessarily generate
  // diagnostics.  These are programmer errors, not user errors.
  if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
  const libspirv::AssemblyGrammar grammar(context);
  if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;

  // Generate friendly names for Ids if requested.
  std::unique_ptr<libspirv::FriendlyNameMapper> friendly_mapper;
  libspirv::NameMapper name_mapper = libspirv::GetTrivialNameMapper();
  if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
    friendly_mapper.reset(
        new libspirv::FriendlyNameMapper(context, code, wordCount));
    name_mapper = friendly_mapper->GetNameMapper();
  }

  // Now disassemble!
  Disassembler disassembler(grammar, options, name_mapper);
  if (auto error = spvBinaryParse(context, &disassembler, code, wordCount,
                                  DisassembleHeader, DisassembleInstruction,
                                  pDiagnostic)) {
    return error;
  }

  return disassembler.SaveTextResult(pText);
}
Exemplo n.º 2
0
int main(){
    stack_t stack;
    struct inf textin;//аша считываемая информация
    int stack_a[maxsize];
    int i, k;
    FILE *mf, *getin, *disa;
    stack.size = 0;
    for (i = 0; i < maxsize; i++)
        stack_a[i] = 0;
    i = 0;
    mf = File1_ctor(mf);
    getin = File2_ctor(getin);
    disa = File3_ctor(disa);
    assembler(getin,stack_a, &stack,&textin);
    disassembler(disa, stack_a);
    while ((stack_a[i-1] !=0) && (stack_a[i] != 0)){
        printf("%d ", stack_a[i]);
        i++;
    }
    dump(&stack, mf);
    File_dtor(disa);
    File_dtor(getin);
    File_dtor(mf);
    return 0;
}
Exemplo n.º 3
0
void Disassembler::Disassemble(InputStream &cboStream, OutputStream &outputStream)
{
	const auto pos = cboStream.GetPosition();
	CboValidator validator;
	CboValidator::Result result = validator.Validate(cboStream);
	cboStream.SetPosition(pos);
	DisassemblerCore disassembler(result, mAllocator, cboStream, outputStream);
	disassembler.Disassemble();
}
Exemplo n.º 4
0
/* Initialize disassembler (libopcodes/libbfd) for given file.
 *
 * If the the function returns data with data.bfd_file = NULL,
 * then the function failed.
 */
static struct disasm_data disasm_init(const char *filename)
{
    asection *section;
    struct disasm_data data;

    static bool initialized = false;
    if (!initialized)
    {
        bfd_init();
        initialized = true;
    }

    data.bfd_file = bfd_openr(filename, NULL);
    if (data.bfd_file == NULL)
    {
        VERB1 log_bfd_error("bfd_openr", filename);
        return data;
    }

    if (!bfd_check_format(data.bfd_file, bfd_object))
    {
        VERB1 log_bfd_error("bfd_check_format", filename);
        goto ret_fail;
    }

    section = bfd_get_section_by_name(data.bfd_file, ".text");
    if (section == NULL)
    {
        VERB1 log_bfd_error("bfd_get_section_by_name", filename);
        goto ret_fail;
    }

    data.disassemble = disassembler(data.bfd_file);
    if (data.disassemble == NULL)
    {
        VERB1 log("Unable to find disassembler");
        goto ret_fail;
    }

    init_disassemble_info(&data.info, NULL, buffer_printf);
    data.info.arch = bfd_get_arch(data.bfd_file);
    data.info.mach = bfd_get_mach(data.bfd_file);
    data.info.buffer_vma = section->vma;
    data.info.buffer_length = section->size;
    data.info.section = section;
    /*TODO: memory error func*/
    bfd_malloc_and_get_section(data.bfd_file, section, &data.info.buffer);
    disassemble_init_for_target(&data.info);

    return data;

ret_fail:
    bfd_close(data.bfd_file);
    data.bfd_file = NULL;
    return data;
}
Exemplo n.º 5
0
int get_instr_length(asm_program_t *prog, bfd_vma addr)
{
  disassembler_ftype disas = disassembler(prog->abfd);
  fprintf_ftype old_fprintf_func = prog->disasm_info.fprintf_func;
  prog->disasm_info.fprintf_func = (fprintf_ftype)ignore;
  assert(disas);
  int len = disas(addr, &prog->disasm_info);
  prog->disasm_info.fprintf_func = old_fprintf_func;
  return len;
}
Exemplo n.º 6
0
int get_instr_length(bincode_t *bin, bfd_vma addr)
{
    disassembler_ftype disas = disassembler(bin->abfd);
    fprintf_ftype old_fprintf_func = bin->disasm_info.fprintf_func;
    bin->disasm_info.fprintf_func = (fprintf_ftype)ignore;
    assert(disas);
    int len = disas(addr, &bin->disasm_info);
    bin->disasm_info.fprintf_func = old_fprintf_func;
    return len;
}
Exemplo n.º 7
0
void
print_insn (ARMword instr)
{
  int size;
  disassembler_ftype disassemble_fn;

  opbuf[0] = 0;
  info.application_data = & instr;
  disassemble_fn = disassembler (bfd_arch_arm, 0, 0, NULL);
  size = disassemble_fn (0, & info);
  fprintf (stderr, " %*s\n", size, opbuf);
}
Exemplo n.º 8
0
int get_instr_length( bhp _p, long long addr )
{
    int len;
    bh* p = (bh*) _p;
    struct disassemble_info* di = p->disasp;
    disassembler_ftype disas = disassembler( p->bfdp );
    fprintf_ftype old_fprintf_func = di->fprintf_func;
    di->fprintf_func = (fprintf_ftype) ignore;
    len = disas( addr, di );
    di->fprintf_func = old_fprintf_func;

    return len;
}
Exemplo n.º 9
0
void print_disasm_rawbytes(enum bfd_architecture arch,
			   bfd_vma addr,
			   const char *buf, int size)
{
  asm_program_t *prog = byte_insn_to_asmp(arch, addr, (unsigned char*)buf, size);
  
  if (!prog)
    return;

  disassembler_ftype disas = disassembler(prog->abfd);
  disas(addr, &prog->disasm_info);
  free_asm_program(prog);
  fflush(stdout);
}
Exemplo n.º 10
0
void Disassemble(const char *cboFileName)
{
	try
	{
		Bond::StdioInputStream cboStream(cboFileName);
		Bond::DefaultAllocator allocator;
		Bond::StdOutOutputStream outputStream;
		Bond::Disassembler disassembler(allocator);
		disassembler.Disassemble(cboStream, outputStream);
	}
	catch (const Bond::Exception &e)
	{
		fprintf(stderr, "%s\n", e.GetMessage());
	}
}
Exemplo n.º 11
0
void arch_bfdDisasm(pid_t pid, uint8_t * mem, size_t size, char *instr)
{
    while (pthread_mutex_lock(&arch_bfd_mutex)) ;

    bfd_init();

    char fname[PATH_MAX];
    snprintf(fname, sizeof(fname), "/proc/%d/exe", pid);
    bfd *bfdh = bfd_openr(fname, NULL);
    if (bfdh == NULL) {
        LOGMSG(l_WARN, "bfd_openr('/proc/%d/exe') failed", pid);
        goto out;
    }

    if (!bfd_check_format(bfdh, bfd_object)) {
        LOGMSG(l_WARN, "bfd_check_format() failed");
        goto out;
    }

    disassembler_ftype disassemble = disassembler(bfdh);
    if (disassemble == NULL) {
        LOGMSG(l_WARN, "disassembler() failed");
        goto out;
    }

    struct disassemble_info info;
    init_disassemble_info(&info, instr, arch_bfdFPrintF);
    info.arch = bfd_get_arch(bfdh);
    info.mach = bfd_get_mach(bfdh);
    info.buffer = mem;
    info.buffer_length = size;
    info.section = NULL;
    info.endian = bfd_little_endian(bfdh) ? BFD_ENDIAN_LITTLE : BFD_ENDIAN_BIG;
    disassemble_init_for_target(&info);

    strcpy(instr, "");
    if (disassemble(0, &info) <= 0) {
        snprintf(instr, _HF_INSTR_SZ, "[DIS-ASM_FAILURE]");
    }

 out:
    bfdh ? bfd_close_all_done(bfdh) : 0;

    while (pthread_mutex_unlock(&arch_bfd_mutex)) ;
    return;
}
Exemplo n.º 12
0
// returns a string which is valid until the next call to this function
char* string_of_insn(asm_program_t *prog, Instruction *inst)
{
  static struct bprintf_buffer bits = {NULL, NULL, 0};

  disassembler_ftype disas = disassembler(prog->abfd);
  fprintf_ftype old_fprintf_func = prog->disasm_info.fprintf_func;
  void *oldstream = prog->disasm_info.stream;
  prog->disasm_info.fprintf_func = (fprintf_ftype)bprintf;
  prog->disasm_info.stream = &bits;

  bits.end = bits.str;
  int len = disas(inst->address, &prog->disasm_info);

  prog->disasm_info.fprintf_func = old_fprintf_func;
  prog->disasm_info.stream = oldstream;
  
  return bits.str;
}
Exemplo n.º 13
0
void NewCpu::Trace()
{
    Disassembler disassembler(_regs.PC.W, _mem);

    DisassembledInstruction instruction;
    disassembler.Disassemble(instruction);

    printf("%04X %-10s %-12s A:%02x X:%02X Y:%02X P:%02X S:%02X\n",
        _regs.PC.W,
        instruction.GetFormattedBytes().c_str(),
        instruction.GetDisassemblyString().c_str(),
        _regs.A,
        _regs.X,
        _regs.Y,
        _regs.P,
        _regs.SP
    );
}
Exemplo n.º 14
0
static void get_asm_insns(uint8_t *image, size_t len, unsigned long base,
			  int opcodes)
{
	int count, i, pc = 0;
	char tpath[256];
	struct disassemble_info info;
	disassembler_ftype disassemble;
	bfd *bfdf;

	memset(tpath, 0, sizeof(tpath));
	get_exec_path(tpath, sizeof(tpath));

	bfdf = bfd_openr(tpath, NULL);
	assert(bfdf);
	assert(bfd_check_format(bfdf, bfd_object));

	init_disassemble_info(&info, stdout, (fprintf_ftype) fprintf);
	info.arch = bfd_get_arch(bfdf);
	info.mach = bfd_get_mach(bfdf);
	info.buffer = image;
	info.buffer_length = len;

	disassemble_init_for_target(&info);

	disassemble = disassembler(bfdf);
	assert(disassemble);

	do {
		printf("%4x:\t", pc);

		count = disassemble(pc, &info);

		if (opcodes) {
			printf("\n\t");
			for (i = 0; i < count; ++i)
				printf("%02x ", (uint8_t) image[pc + i]);
		}
		printf("\n");

		pc += count;
	} while(count > 0 && pc < len);

	bfd_close(bfdf);
}
Exemplo n.º 15
0
spv_result_t spvBinaryToText(const spv_const_context context,
                             const uint32_t* code, const size_t wordCount,
                             const uint32_t options, spv_text* pText,
                             spv_diagnostic* pDiagnostic) {
  // Invalid arguments return error codes, but don't necessarily generate
  // diagnostics.  These are programmer errors, not user errors.
  if (!pDiagnostic) return SPV_ERROR_INVALID_DIAGNOSTIC;
  const libspirv::AssemblyGrammar grammar(context);
  if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;

  Disassembler disassembler(grammar, options);
  if (auto error = spvBinaryParse(context, &disassembler, code, wordCount,
                                  DisassembleHeader, DisassembleInstruction,
                                  pDiagnostic)) {
    return error;
  }

  return disassembler.SaveTextResult(pText);
}
Exemplo n.º 16
0
// returns a string which is valid until the next call to this function
char* asmir_string_of_insn(asm_program_t *prog, bfd_vma inst)
{
  static struct bprintf_buffer bits = {NULL, NULL, 0};

  disassembler_ftype disas = disassembler(prog->abfd);
  fprintf_ftype old_fprintf_func = prog->disasm_info.fprintf_func;
  void *oldstream = prog->disasm_info.stream;

  prog->disasm_info.disassembler_options = "intel";
  prog->disasm_info.fprintf_func = (fprintf_ftype)bprintf;
  prog->disasm_info.stream = &bits;

  bits.end = bits.str;
  
  disas(inst, &prog->disasm_info);

  prog->disasm_info.fprintf_func = old_fprintf_func;
  prog->disasm_info.stream = oldstream;
  
  return bits.str;
}
Exemplo n.º 17
0
bool Compare(const std::vector<u16> &code1, const std::vector<u16> &code2)
{
	if (code1.size() != code2.size())
		printf("Size difference! 1=%i 2=%i\n", (int)code1.size(), (int)code2.size());
	u32 count_equal = 0;
	const int min_size = std::min<int>(code1.size(), code2.size());

	AssemblerSettings settings;
	DSPDisassembler disassembler(settings);
	for (int i = 0; i < min_size; i++)
	{
		if (code1[i] == code2[i])
		{
			count_equal++;
		}
		else
		{
			std::string line1, line2;
			u16 pc = i;
			disassembler.DisassembleOpcode(&code1[0], 0x0000, 2, &pc, line1);
			pc = i;
			disassembler.DisassembleOpcode(&code2[0], 0x0000, 2, &pc, line2);
			printf("!! %04x : %04x vs %04x - %s  vs  %s\n", i, code1[i], code2[i], line1.c_str(), line2.c_str());
		}
	}
	if (code2.size() != code1.size())
	{
		printf("Extra code words:\n");
		const std::vector<u16> &longest = code1.size() > code2.size() ? code1 : code2;
		for (int i = min_size; i < (int)longest.size(); i++)
		{
			u16 pc = i;
			std::string line;
			disassembler.DisassembleOpcode(&longest[0], 0x0000, 2, &pc, line);
			printf("!! %s\n", line.c_str());
		}
	}
	printf("Equal instruction words: %i / %i\n", count_equal, min_size);
	return code1.size() == code2.size() && code1.size() == count_equal;
}
Exemplo n.º 18
0
char* disasm( bhp _p,
              unsigned long long addr )
{
    static struct bprintf_buffer bits = {NULL, NULL, 0};

    bh* p = (bh*) _p;
    struct disassemble_info* di = p->disasp;
    disassembler_ftype disas = disassembler( p->bfdp );
    fprintf_ftype old_fprintf_func = di->fprintf_func;
    void *oldstream = di->stream;
    di->fprintf_func = (fprintf_ftype) bprintf;
    di->stream = &bits;

    bits.end = bits.str;

    disas( addr, di );

    di->fprintf_func = old_fprintf_func;
    di->stream = oldstream;

    return bits.str;
}
Exemplo n.º 19
0
bool disas_libopcode(FILE *fp_out, const char *machine, bool big_endian,
		     uint64_t addr, void *buf, size_t len)
{
	bfd *abfd = NULL;
	struct disassemble_info inf;
	const bfd_arch_info_type *arch_inf = bfd_scan_arch (machine);
	disassembler_ftype disas_fn;
	int size, pos;

	if (!arch_inf) {
		return false;
	}

	abfd = bfd_openr("/dev/null", "binary");
	abfd->arch_info = arch_inf;

	init_disassemble_info (&inf, fp_out, (fprintf_ftype) fprintf);
	inf.buffer = buf;
	inf.buffer_vma = addr;
	inf.buffer_length = len;
	inf.endian = big_endian ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
	inf.print_address_func = print_address;

	disassemble_init_for_target(&inf);

	disas_fn = disassembler (abfd);
	pos = 0;
	do {
		fprintf(fp_out, "%" PRIx64 "\t", addr + pos);
		size = disas_fn(addr + pos, &inf);
		pos += size;
		fputc('\n', fp_out);
	} while (pos < len);
	bfd_close(abfd);
	return true;
}
Exemplo n.º 20
0
Arquivo: disasm.c Projeto: abrt/satyr
struct sr_disasm_state *
sr_disasm_init(const char *file_name,
               char **error_message)
{
#if HAVE_LIBOPCODES
    struct sr_disasm_state *state =
        sr_malloc(sizeof(struct sr_disasm_state));

    state->bfd_file = bfd_openr(file_name, NULL);
    if (!state->bfd_file)
    {
        *error_message = sr_asprintf("Failed to open file %s: %s",
                                     file_name,
                                     bfd_errmsg(bfd_get_error()));
        free(state);
        return NULL;
    }

    if (!bfd_check_format(state->bfd_file, bfd_object))
    {
        *error_message = sr_asprintf("Invalid file format of %s: %s",
                                     file_name,
                                     bfd_errmsg(bfd_get_error()));
        bfd_close(state->bfd_file);
        free(state);
        return NULL;
    }

    asection *section =
        bfd_get_section_by_name(state->bfd_file, ".text");

    if (!section)
    {
        *error_message = sr_asprintf(
            "Failed to find .text section in %s: %s",
            file_name,
            bfd_errmsg(bfd_get_error()));

        bfd_close(state->bfd_file);
        free(state);
        return NULL;
    }

    state->disassembler = disassembler(state->bfd_file);
    if (!state->disassembler)
    {
        *error_message = sr_asprintf(
            "Unable to find disassembler for %s",
            file_name);

        bfd_close(state->bfd_file);
        free(state);
        return NULL;
    }

    init_disassemble_info(&state->info, NULL, buffer_printf);
    state->info.arch = bfd_get_arch(state->bfd_file);
    state->info.mach = bfd_get_mach(state->bfd_file);
    state->info.buffer_vma = section->vma;
    state->info.buffer_length = section->size;
    state->info.section = section;
    /* TODO: memory error func */
    bfd_malloc_and_get_section(state->bfd_file, section,
                               &state->info.buffer);

    disassemble_init_for_target(&state->info);
    return state;
#else // HAVE_LIBOPCODES
    *error_message = sr_asprintf("satyr compiled without libopcodes");
    return NULL;
#endif // HAVE_LIBOPCODES
}
Exemplo n.º 21
0
disassembler::disassembler()
{
    disassembler(NULL);
}
Exemplo n.º 22
0
void init_disassemble(){
	abfd = malloc(sizeof(bfd));
	init_disassemble_info (&disasm_info, stdout, (fprintf_ftype) fprintf);
	disasm_info.print_address_func = objdump_print_address;
	disasm_info.symbol_at_address_func = objdump_symbol_at_address;

	/*
	 * choose arch infor since we will select different disassemble function.
	 */
	generic_arch_t* arch_instance = get_arch_instance("");
	machine = arch_instance->arch_name;	
	const bfd_arch_info_type *info = bfd_scan_arch (machine);
	if (info == NULL){
        	//fatal (_("Can't use supplied machine %s"), machine);
		printf("Can't use supplied machine %s\n", machine);
		return;
	}

	abfd->arch_info = info;
	
	/*
	 * endian selection
	 */
	if (endian != BFD_ENDIAN_UNKNOWN)
	{
		struct bfd_target *xvec;

		xvec = xmalloc (sizeof (struct bfd_target));
		//memcpy (xvec, abfd->xvec, sizeof (struct bfd_target));
		xvec->byteorder = endian;
		abfd->xvec = xvec;
	}
	/* Get a disassemble function according to the arch and endian of abfd */
	disassemble_fn = disassembler (abfd);
	if(!disassemble_fn)
	{
      /*
	non_fatal (_("Can't disassemble for architecture %s\n"),
                 bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
	*/
		printf("Can't disassemble for architecture %s\n", bfd_printable_arch_mach (bfd_get_arch (abfd), 0));
		exit_status = 1;
		return;
	}

	disasm_info.flavour = bfd_get_flavour (abfd);
	disasm_info.arch = bfd_get_arch (abfd);
	disasm_info.mach = bfd_get_mach (abfd);
	disasm_info.disassembler_options = disassembler_options;
	disasm_info.octets_per_byte = bfd_octets_per_byte (abfd);
	disasm_info.skip_zeroes = DEFAULT_SKIP_ZEROES;
	disasm_info.skip_zeroes_at_end = DEFAULT_SKIP_ZEROES_AT_END;
	disasm_info.disassembler_needs_relocs = FALSE;

#if 1
	if (bfd_big_endian (abfd))
		disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_BIG;
	else if (bfd_little_endian (abfd))
		disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
	else
 /* ??? Aborting here seems too drastic.  We could default to big or little
       instead.  */
	disasm_info.endian = BFD_ENDIAN_UNKNOWN;
#endif
	/* set the default endianess is BFD_ENDIAN_LITTLE */
	disasm_info.display_endian = disasm_info.endian = BFD_ENDIAN_LITTLE;
	disasm_info.symtab = sorted_syms;
	disasm_info.symtab_size = sorted_symcount;
	disasm_info.read_memory_func = disasm_read_memory;
	free (sorted_syms);
}
Exemplo n.º 23
0
uv_err_t UVDBfdInstructionIterator::init() {
    bfd *a_bfd = NULL;

    uv_assert_ret(m_obj);
    uv_assert_ret(m_obj->m_bfd);
    a_bfd = m_obj->m_bfd;

    //Needs to be an object or an archive
    if( !bfd_check_format(a_bfd, bfd_object)
            && !bfd_check_format(a_bfd, bfd_archive) )
    {
        //bfd_close(a_bfd);
        printf("bad file\n");
        return UV_DEBUG(UV_ERR_GENERAL);
    }
    printf("BFD open and is object\n");

    /*
    Standard disassemblers.  Disassemble one instruction at the given
    target address.  Return number of octets processed.
    typedef int (*disassembler_ftype) (bfd_vma, disassemble_info *);
    */
    g_disassembler_function = disassembler(a_bfd);
    if( !g_disassembler_function ) {
        printf("failed \n");
        return UV_DEBUG(UV_ERR_GENERAL);
    }

    memset(&m_disasm_info, 0, sizeof(m_disasm_info));
    init_disassemble_info(&m_disasm_info, stdout, (fprintf_ftype) fprintf);
    m_disasm_info.flavour = bfd_get_flavour (a_bfd);
    m_disasm_info.arch = bfd_get_arch (a_bfd);
    m_disasm_info.mach = bfd_get_mach (a_bfd);
    m_disasm_info.disassembler_options = NULL;
    m_disasm_info.octets_per_byte = bfd_octets_per_byte(a_bfd);
    m_disasm_info.skip_zeroes = 0;
    m_disasm_info.skip_zeroes_at_end = 0;
    m_disasm_info.disassembler_needs_relocs = FALSE;
    m_disasm_info.display_endian = m_disasm_info.endian = BFD_ENDIAN_BIG;

    //Don't care
    m_disasm_info.application_data = NULL;
    m_disasm_info.print_address_func = objdump_print_address;
    m_disasm_info.symbol_at_address_func = objdump_symbol_at_address;

    disassemble_init_for_target(&m_disasm_info);

    //Wonder if these can be NULL?
    m_disasm_info.symtab = NULL;
    m_disasm_info.symtab_size = 0;

    /*
    This won't work since we want to step on our own accord
    bfd_map_over_sections(a_bfd, disassemble_section, &disasm_info);
    */
#if 0
    void
    bfd_map_over_sections (bfd *abfd,
                           void (*operation) (bfd *, asection *, void *),
                           void *user_storage)
    {
        asection *sect;
        unsigned int i = 0;

        for (sect = abfd->sections; sect != NULL; i++, sect = sect->next)
            (*operation) (abfd, sect, user_storage);

        if (i != abfd->section_count)	/* Debugging */
            abort ();
    }
Exemplo n.º 24
0
  void LLVMState::show_machine_code(void* buffer, size_t size) {

#if defined(IS_X86) || defined(IS_X8664)
#ifndef RBX_WINDOWS
    ud_t ud;

    ud_init(&ud);
#ifdef IS_64BIT_ARCH
    ud_set_mode(&ud, 64);
#else
    ud_set_mode(&ud, 32);
#endif
    ud_set_syntax(&ud, UD_SYN_ATT);
    ud_set_input_buffer(&ud, reinterpret_cast<uint8_t*>(buffer), size);

    while(ud_disassemble(&ud)) {
      void* address = reinterpret_cast<void*>(
          reinterpret_cast<uintptr_t>(buffer) + ud_insn_off(&ud));

      llvm::outs() << format("%10p", address) << "  ";
      llvm::outs() << format("%-24s", ud_insn_asm(&ud));
      if(ud.operand[0].type == UD_OP_JIMM) {
        const void* addr = (const void*)((uintptr_t)buffer + ud.pc + (int)ud.operand[0].lval.udword);
        llvm::outs() << " ; " << addr;
        if(ud.mnemonic == UD_Icall) {
          Dl_info info;
          if(dladdr((void*)addr, &info)) {
            int status = 0;
            char* cpp_name = abi::__cxa_demangle(info.dli_sname, 0, 0, &status);
            if(status >= 0) {
              // Chop off the arg info from the signature output
              char *paren = strstr(cpp_name, "(");
              *paren = 0;
              llvm::outs() << " " << cpp_name;
              free(cpp_name);
            } else {
              llvm::outs() << " " << info.dli_sname;
            }
          }
        }
      }

      for(uint8_t i = 0; i < 2; i++) {
        if(ud.operand[i].type == UD_OP_IMM) {
          Dl_info info;
          if(dladdr((void*)ud.operand[i].lval.uqword, &info)) {
            llvm::outs() << " ; " << info.dli_sname;
            break; // only do one
          }
        }
      }

      llvm::outs() << "\n";
    }
#endif  // !RBX_WINDOWS

#else
    JITDisassembler disassembler(buffer, size);
    std::string output = disassembler.print_machine_code();
    std::cout << output;
#endif // !IS_X86

  }
Exemplo n.º 25
0
void disNCS(const Common::UString &inFile, const Common::UString &outFile,
            Aurora::GameID &game, Command &command, bool printStack, bool printControlTypes) {

	Common::SeekableReadStream *ncs = new Common::ReadFile(inFile);

	Common::WriteStream *out = 0;
	try {
		if (!outFile.empty())
			out = new Common::WriteFile(outFile);
		else
			out = new Common::StdOutStream;

		status("Disassembling script...");
		NWScript::Disassembler disassembler(*ncs, game);

		if (game != Aurora::kGameIDUnknown) {
			try {
				status("Analyzing script stack...");
				disassembler.analyzeStack();
			} catch (...) {
				Common::exceptionDispatcherWarnAndIgnore("Script analysis failed");
			}

			try {
				status("Analyzing control flow...");
				disassembler.analyzeControlFlow();
			} catch (...) {
				Common::exceptionDispatcherWarnAndIgnore("Control flow analysis failed");
			}
		}

		switch (command) {
			case kCommandListing:
				disassembler.createListing(*out, printStack);
				break;

			case kCommandAssembly:
				disassembler.createAssembly(*out, printStack);
				break;

			case kCommandDot:
				disassembler.createDot(*out, printControlTypes);
				break;

			default:
				throw Common::Exception("Invalid command %u", (uint)command);
		}

	} catch (...) {
		delete ncs;
		delete out;
		throw;
	}

	out->flush();

	if (!outFile.empty())
		status("Disassembled \"%s\" into \"%s\"", inFile.c_str(), outFile.c_str());

	delete ncs;
	delete out;
}
Exemplo n.º 26
0
void SourceAssembler::emit(int instr) {
  stream()->print("\t");
  disassembler().disasm(NULL, instr);
  emit_comment_and_cr();
}
Exemplo n.º 27
0
/*
 * Implementation
 */
void
jit_init_debug(const char *progname)
{
#if DISASSEMBLER
    bfd_init();

    if (progname)
	disasm_bfd = bfd_openr(progname, NULL);
    if (disasm_bfd == NULL) {
#if defined(__linux__)
	disasm_bfd = bfd_openr("/proc/self/exe", NULL);
	if (disasm_bfd == NULL)
#endif
	    return;
    }
    bfd_check_format(disasm_bfd, bfd_object);
    bfd_check_format(disasm_bfd, bfd_archive);
    disasm_print = disassembler(disasm_bfd);
    assert(disasm_print);
    INIT_DISASSEMBLE_INFO(disasm_info, disasm_stream, fprintf);
#  if defined(__i386__) || defined(__x86_64__)
    disasm_info.arch = bfd_arch_i386;
#    if defined(__x86_64__)
#      if __WORDSIZE == 32
    disasm_info.mach = bfd_mach_x64_32;
#      else
    disasm_info.mach = bfd_mach_x86_64;
#      endif
#    else
    disasm_info.mach = bfd_mach_i386_i386;
#    endif
#  endif
#  if defined(__powerpc__)
    disasm_info.arch = bfd_arch_powerpc;
    disasm_info.mach = bfd_mach_ppc64;
#    if HAVE_DISASSEMBLE_INIT_FOR_TARGET
    disassemble_init_for_target(&disasm_info);
#    elif HAVE_DISASSEMBLE_INIT_POWERPC
    disassemble_init_powerpc(&disasm_info);
#    endif
#    if defined(__powerpc64__)
    disasm_info.disassembler_options = "64";
#    endif
#    if HAVE_DISASSEMBLE_INIT_FOR_TARGET
    disassemble_init_for_target(&disasm_info);
#    elif HAVE_DISASSEMBLE_INIT_POWERPC
    disassemble_init_powerpc(&disasm_info);
#    endif
#  endif
#  if defined(__sparc__)
    disasm_info.endian = disasm_info.display_endian = BFD_ENDIAN_BIG;
#  endif
#  if defined(__s390__) || defined(__s390x__)
    disasm_info.arch = bfd_arch_s390;
#    if __WORDSIZE == 32
    disasm_info.mach = bfd_mach_s390_31;
#    else
    disasm_info.mach = bfd_mach_s390_64;
#    endif
    disasm_info.endian = disasm_info.display_endian = BFD_ENDIAN_BIG;
    disasm_info.disassembler_options = "zarch";
#  endif
#  if defined(__alpha__)
    disasm_info.arch = bfd_arch_alpha;
    disasm_info.mach = bfd_mach_alpha_ev6;
#  endif
    disasm_info.print_address_func = disasm_print_address;

    if (bfd_get_file_flags(disasm_bfd) & HAS_SYMS) {
	asymbol		**in;
	asymbol		**out;
	asymbol		 *symbol;
	long		  offset;
	long		  sym_count;
	long		  dyn_count;
	long		  sym_storage;
	long		  dyn_storage;

	if ((sym_storage = bfd_get_symtab_upper_bound(disasm_bfd)) >= 0) {

	    if (bfd_get_file_flags(disasm_bfd) & DYNAMIC) {
		dyn_storage = bfd_get_dynamic_symtab_upper_bound(disasm_bfd);
#  if defined(__alpha__)
		/* XXX */
		if (dyn_storage < 0)
		    dyn_storage = 0;
#  else
		assert(dyn_storage >= 0);
#  endif
	    }
	    else
		dyn_storage = 0;

	    jit_alloc((jit_pointer_t *)&disasm_symbols,
		      (sym_storage + dyn_storage) * sizeof(asymbol *));
	    sym_count = bfd_canonicalize_symtab(disasm_bfd, disasm_symbols);
	    assert(sym_count >= 0);
	    if (dyn_storage) {
		dyn_count = bfd_canonicalize_dynamic_symtab(disasm_bfd,
							    disasm_symbols +
							    sym_count);
		assert(dyn_count >= 0);
	    }
	    else
		dyn_count = 0;
	    disasm_num_symbols = sym_count + dyn_count;

	    disasm_num_synthetic = bfd_get_synthetic_symtab(disasm_bfd,
							    sym_count,
							    disasm_symbols,
							    dyn_count,
							    disasm_symbols +
							    sym_count,
							    &disasm_synthetic);
	    if (disasm_num_synthetic > 0) {
		jit_realloc((jit_pointer_t *)&disasm_symbols,
			    (sym_storage + dyn_storage) * sizeof(asymbol *),
			    (sym_storage + dyn_storage + disasm_num_synthetic) *
			    sizeof(asymbol *));
		for (offset = 0; offset < disasm_num_synthetic; offset++)
		    disasm_symbols[disasm_num_symbols++] =
			disasm_synthetic + offset;
	    }

	    /* remove symbols not useful for disassemble */
	    in = out = disasm_symbols;
	    for (offset = 0; offset < disasm_num_symbols; offset++) {
		symbol = *in++;
		if (symbol->name &&
		    symbol->name[0] != '\0' &&
		    !(symbol->flags & (BSF_DEBUGGING | BSF_SECTION_SYM)) &&
		    !bfd_is_und_section(symbol->section) &&
		    !bfd_is_com_section(symbol->section))
		    *out++ = symbol;
	    }
	    disasm_num_symbols = out - disasm_symbols;
	    qsort(disasm_symbols, disasm_num_symbols,
		  sizeof(asymbol *), disasm_compare_symbols);
	}
    }
#endif
}