Ejemplo n.º 1
0
int symbol_init(struct kvm *kvm)
{
	int ret = 0;

	if (!kvm->vmlinux)
		return -EINVAL;

	bfd_init();

	abfd = bfd_openr(kvm->vmlinux, NULL);
	if (abfd == NULL) {
		bfd_error_type err = bfd_get_error();

		switch (err) {
		case bfd_error_no_memory:
			ret = -ENOMEM;
			break;
		case bfd_error_invalid_target:
			ret = -EINVAL;
			break;
		default:
			ret = -EFAULT;
			break;
		}
	}

	return ret;
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
	int len, klen, opcodes = 0;
	char *kbuff;
	unsigned long base;
	uint8_t image[4096];

	if (argc > 1) {
		if (!strncmp("-o", argv[argc - 1], 2)) {
			opcodes = 1;
		} else {
			printf("usage: bpf_jit_disasm [-o: show opcodes]\n");
			exit(0);
		}
	}

	bfd_init();
	memset(image, 0, sizeof(image));

	kbuff = get_klog_buff(&klen);

	len = get_last_jit_image(kbuff, klen, image, sizeof(image), &base);
	if (len > 0 && base > 0)
		get_asm_insns(image, len, base, opcodes);

	put_klog_buff(kbuff);

	return 0;
}
Ejemplo n.º 3
0
int BinaryFile::Init(char *filename)
{
	Destroy();

	bfd_init();

	_abfd = bfd_openr(filename, NULL); 
	if (_abfd == NULL) { 
		perror("bfd_openr");
		return -1;
	} 
	bfd_boolean ret = bfd_check_format(_abfd, bfd_object);
	if (ret == false) { 
		perror("bfd_check_format_matches");
		return -2;
	}

	int result = InitSymbols(_symbols, SYM_FUNC);
	if (result < 0) {
		fprintf(stderr, "get symbols error!\n");
		return -3;
	}
	result = InitRelsym(_rels);
	if (result < 0) {
		fprintf(stderr, "get rels error!\n");
		return -3;
	}
	return 0;
}
Ejemplo n.º 4
0
void objdump(const char *path)
{
    bfd_init();

    bfd *abfd = bfd_openr(path, NULL);

    if (abfd == NULL)
        errx(1, bfd_errmsg(bfd_get_error()));

    if (!bfd_check_format(abfd, bfd_object)) {
        bfd_close_all_done(abfd);
        errx(1, "File is not a valid object file.");
    }

    printf("%s:     file format %s\n", path, bfd_get_target(abfd));
    printf("architecture: %s, flags: 0x%08x\n", bfd_printable_arch_mach(bfd_get_arch(abfd), bfd_get_mach(abfd)), abfd->flags);
    printf("start address 0x%016lx", bfd_get_start_address(abfd));
    printf("\n");
    printf("Sections:\n");
    printf("Idx Name          Size      VMA               LMA               File off  Algn\n");
    printf("                  Flags    Content\n");

    object_stats stats = { FALSE, FALSE };
    bfd_map_over_sections(abfd, (void (*)(bfd *, asection *, void *))print_section, &stats);

    if (stats.contains_hello && stats.contains_world)
        printf("\nThis file might be a hello world program!\n");

    bfd_close(abfd);
}
Ejemplo n.º 5
0
int
main (int argc, char **argv)
{
  int c;
  char *target = default_target;

  program_name = *argv;
  xmalloc_set_program_name (program_name);

  bfd_init ();
  set_default_bfd_target ();

  while ((c = getopt_long (argc, argv, "aip0svb?",
                           long_options, (int *) 0)) != EOF)
    switch (c)
      {
      case 'a' :
        sort_by_address = 1;
        break;
      case 'v' :
        verbose = 1;
        break;
      case 'p' :
        physical_addresses = 1;
        break;
      case 'i' :
        physical_addresses = 0;
        break;
      case '0' :
        a0_address_mapping = 1;
        break;
      case 's' :
        a0_address_mapping = 0;
        break;
      case 'b' :
        target = optarg;
        break;
      case '?' :
        show_usage = 1;
        break;
      default :
        show_usage = 1;
	break;
      }

  if (show_usage)
    usage (stdout, 0);

  if (optind == argc)
  {
    char *file = strdup ("a.out");
    hexify_file (file, target);
    free (file);
  }
  else
    for (; optind < argc;)
      hexify_file (argv[optind++], target);

  return exit_status;
}
Ejemplo n.º 6
0
/* use the bfd for the process exe to initialize disassembler.
   FIXME: Invetigate removing this dependency.
*/
static void initdisassembler() {
  char myexepath[PATH_MAX];
  char *target = NULL;

  if (init_done == 1)  return;

  /* find the victim executable */
  int mypid = getpid();
  sprintf(myexepath, "/proc/%d/exe", mypid);

  bfd_init();

  abfd = bfd_openr(myexepath,target);

  if (!abfd) {
    /*error no bfd to disassemble */
    fprintf(stderr, "Could not load bfd for %s\n",myexepath);
    return;
  }

  /* make sure it's an object file */
  if (!bfd_check_format (abfd, bfd_object)) {
    fprintf(stderr, "The bfd %s is not an object file\n",myexepath);
    return;
  }

  init_done = 1;
}
Ejemplo n.º 7
0
extern bool getResourceFromFile(const char *filename, MemoryBuffer &data, const char * type, unsigned id)
{
#ifdef _WIN32
    HINSTANCE dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
    if (dllHandle == NULL)
        dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE); // the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag is not supported on all versions of Windows
    if (dllHandle == NULL)
    {
        DBGLOG("Failed to load library %s: %d", filename, GetLastError());
        return false;
    }
    HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
    if (!hrsrc)
        return false;
    size32_t len = SizeofResource(dllHandle, hrsrc);
    const void *rdata = (const void *) LoadResource(dllHandle, hrsrc);
    data.append(len, rdata);
    FreeLibrary(dllHandle);
    return true;
#else
    bfd_init ();
    bfd *file = bfd_openr(filename, NULL);
    if (file)
    {
        StringBuffer sectionName;
        sectionName.append(type).append("_").append(id).append(".data");
        SecScanParam param(data, sectionName.str());
        if (bfd_check_format (file, bfd_object))
            bfd_map_over_sections (file, secscan, &param);
        bfd_close (file);
   }
   return data.length() != 0;
#endif
}
Ejemplo n.º 8
0
extern bool getResourceFromFile(const char *filename, MemoryBuffer &data, const char * type, unsigned id)
{
#ifdef _WIN32
    HINSTANCE dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
    if (dllHandle == NULL)
        dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE); // the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag is not supported on all versions of Windows
    if (dllHandle == NULL)
    {
        DBGLOG("Failed to load library %s: %d", filename, GetLastError());
        return false;
    }
    HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
    if (!hrsrc)
        return false;
    size32_t len = SizeofResource(dllHandle, hrsrc);
    const void *rdata = (const void *) LoadResource(dllHandle, hrsrc);
    data.append(len, rdata);
    FreeLibrary(dllHandle);
    return true;
#elif defined (_USE_BINUTILS)
    CriticalBlock block(bfdCs);
    bfd_init ();
    bfd *file = bfd_openr(filename, NULL);
    if (file)
    {
        StringBuffer sectionName;
        sectionName.append(type).append("_").append(id).append(".data");
        SecScanParam param(data, sectionName.str());
        if (bfd_check_format (file, bfd_object))
            bfd_map_over_sections (file, secscan, &param);
        bfd_close (file);
   }
   return data.length() != 0;
#else
    struct stat stat_buf;
    VStringBuffer sectname("%s_%u", type, id);
    int fd = open(filename, O_RDONLY);
    if (fd == -1 || fstat(fd, &stat_buf) == -1)
    {
        DBGLOG("Failed to load library %s: %d", filename, errno);
        return false;
    }

    bool ok = false;
    __uint64 size = stat_buf.st_size;
    const byte *start_addr = (const byte *) mmap(0, size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
    if (start_addr == MAP_FAILED)
    {
        DBGLOG("Failed to load library %s: %d", filename, errno);
    }
    else
    {
        ok = getResourceFromMappedFile(filename, start_addr, data, type, id);
        munmap((void *)start_addr, size);
    }
    close(fd);
    return ok;
#endif
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
    bfd *abfd;
    asection *text;
    long storage_needed;
    asymbol **symbol_table;
    long number_of_symbols;
    long i;
    char **matching;
    sec_ptr section;
    char *symbol_name;
    long symbol_offset, section_vma, symbol_address;

    if (argc < 2)
        return 0;
    printf("Open %s\n", argv[1]);
    bfd_init();
    abfd = bfd_openr(argv[1],NULL);
    if (abfd == (bfd *) 0) {
        bfd_perror("bfd_openr");
        return -1;
    }
    if (!bfd_check_format_matches(abfd, bfd_object, &matching)) {
        return -1;
    }
    if (!(bfd_get_file_flags (abfd) & HAS_SYMS)) {
        printf("ERROR flag!\n");
        return -1;
    }
    if ((storage_needed = bfd_get_symtab_upper_bound(abfd)) < 0)
        return -1;
    symbol_table = (asymbol **) xmalloc(storage_needed);
    number_of_symbols = bfd_canonicalize_symtab(abfd, symbol_table);
    if (number_of_symbols < 0)
        return -1;
    fun_table = (FUN_TABLE **)malloc(sizeof(FUN_TABLE)*number_of_symbols);
    bzero(fun_table, sizeof(FUN_TABLE)*number_of_symbols);

    for (i = 0; i < number_of_symbols; i++) {
        if (symbol_table[i]->flags & (BSF_FUNCTION|BSF_GLOBAL)) {
            section = symbol_table[i]->section;
            section_vma = bfd_get_section_vma(abfd, section);
            symbol_name = symbol_table[i]->name;
            symbol_offset = symbol_table[i]->value;
            symbol_address = section_vma + symbol_offset;
            if (section->flags & SEC_CODE) {
                add_function_table(symbol_name,
                                   symbol_address);
            }
        }
    }
    bfd_close(abfd);
    /* 將函式對照表作排序 */
    qsort(fun_table, table_count, sizeof(FUN_TABLE), compare_function);
    dump_function_table();
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
0
void setup (void) {
	bfd_init();
	test_target = bfd_fopen((const char*) "/usr/bin/uname", "default", "r", -1);
	ck_assert_ptr_ne(test_target, NULL);
	ck_assert_str_eq(test_target->filename, "/usr/bin/uname");
	ck_assert_int_ne(test_target->section_count, 0);

	ck_assert_int_ne(test_target->arch_info, 0);
	ck_assert_str_eq(test_target->arch_info->printable_name, "foo");
}
Ejemplo n.º 12
0
extern void DEBUG_LoadSymbols( const char *name )
{
    bfd* abfd;
    char **matching;

    bfd_init();
    abfd = bfd_openr(name, "default");
    if (abfd == NULL) {
        barf("can't open executable %s to get symbol table", name);
    }
    if (!bfd_check_format_matches (abfd, bfd_object, &matching)) {
        barf("mismatch");
    }

    {
        long storage_needed;
        asymbol **symbol_table;
        long number_of_symbols;
        long num_real_syms = 0;
        long i;

        storage_needed = bfd_get_symtab_upper_bound (abfd);

        if (storage_needed < 0) {
            barf("can't read symbol table");
        }
        symbol_table = (asymbol **) stgMallocBytes(storage_needed,"DEBUG_LoadSymbols");

        number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);

        if (number_of_symbols < 0) {
            barf("can't canonicalise symbol table");
        }

        if (add_to_fname_table == NULL)
            add_to_fname_table = allocHashTable();

        for( i = 0; i != number_of_symbols; ++i ) {
            symbol_info info;
            bfd_get_symbol_info(abfd,symbol_table[i],&info);
            if (isReal(info.type, info.name)) {
                insertHashTable(add_to_fname_table,
                                info.value, (void*)info.name);
                num_real_syms += 1;
            }
        }

        IF_DEBUG(interpreter,
                 debugBelch("Loaded %ld symbols. Of which %ld are real symbols\n",
                         number_of_symbols, num_real_syms)
                 );

        stgFree(symbol_table);
    }
}
Ejemplo n.º 13
0
stacktrace::stacktrace ()
  : syms (0)
  , dbfd ()
  , pc (0)
  , filename ("file")
  , funcname ("func")
  , line (0)
  , found (false)
{
  bfd_init ();
  xassert (pthread_mutex_init (&mtx, NULL) == 0);
}
Ejemplo n.º 14
0
static void resolve(unw_word_t addr, const char** file, unsigned int* line, const char** func)
{
	static bool can_give_lineinfo = true;

	if (!can_give_lineinfo)
	{
		return;
	}

	if (!current_executable)
	{
		static char exec_name[PATH_MAX];
		int len = readlink("/proc/self/exe", exec_name, PATH_MAX);
		if (len < 0)
		{
			std::cerr << "Unable to find the current executable, so backtrace won't display line information." << std::endl;
			can_give_lineinfo = false;
			return;
		}

		bfd_init();
		current_executable = bfd_openr(exec_name, 0);

		if (!current_executable)
		{
			std::cerr << "Unable to initialize libbfd, so backtrace won't display line information." << std::endl;
			can_give_lineinfo = false;
			return;
		}

		/* this is a required check. no idea why. */
		bfd_check_format(current_executable, bfd_object);

		unsigned storage_needed = bfd_get_symtab_upper_bound(current_executable);
		syms = (asymbol**) malloc(storage_needed);
		unsigned cSymbols = bfd_canonicalize_symtab(current_executable, syms);

		/* Get the text section so we can 'un-relocate' symbols. */
		text = bfd_get_section_by_name(current_executable, ".text");
	}

	unsigned offset = addr - text->vma;

	if (offset > 0)
	{
		/* Address is in the current executable! Great! */
		int success = bfd_find_nearest_line(current_executable, text, syms, offset, file, func, line);
		if (*file && success)
		{
			return;
		}
	}
}
Ejemplo n.º 15
0
int main(int argc, const char* argv[])
{
	const char* filename = argv[1];
	const char *target = "elf64-x86-64";
	
	bfd *abfd;
	bfd_init();
	abfd = bfd_openr(filename, target);
	if (abfd == NULL) { fprintf(stderr, "getsyms: '%s' : No such file", filename); return 0;  }
	bfd_check_format(abfd, bfd_object);
	dump_symbols(abfd);	
	return 0;
}
Ejemplo n.º 16
0
static LONG WINAPI exception_filter (LPEXCEPTION_POINTERS info)
{
	struct output_buffer ob;
	SYSTEMTIME timeInfo;
	OSVERSIONINFOEX osInfo;
	FILE* crash;
	const char* dumpFile = "crashdump.txt";
	int ret;

	GetSystemTime(&timeInfo);

	OBJZERO(osInfo);
	osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if (!GetVersionEx((OSVERSIONINFO*)&osInfo)) {
		osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		GetVersionEx((OSVERSIONINFO*)&osInfo);
	}

	output_init(&ob, g_output, BUFFER_MAX);

	if (!SymInitialize(GetCurrentProcess(), 0, TRUE)) {
		output_print(&ob, "Failed to init symbol context\n");
	} else {
		struct bfd_set *set = (struct bfd_set *)calloc(1, sizeof(*set));
		bfd_init();
		_backtrace(&ob, set, 128, info->ContextRecord);
		release_set(set);

		SymCleanup(GetCurrentProcess());
	}

	crash = fopen(dumpFile, "w");
	if (crash != nullptr) {
		fprintf(crash, "======start======\n");
		fprintf(crash, "Date: %.4d-%.2d-%.2d\n",
				timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay);
		fprintf(crash, "Windows version %lu.%lu (Build %lu) %s\n",
				osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.szCSDVersion);
		fprintf(crash, BUILDSTRING ", cpu: " CPUSTRING ", version: " UFO_VERSION "\n\n");
		fprintf(crash, "%s", g_output);
		fprintf(crash, "======end========\n");
		fclose(crash);
	}
	fputs(g_output, stderr);

	ret = MessageBox(nullptr, "Would you like to upload this crash dump and your ufoconsole.log? This will help the developers to fix the problem.", GAME_TITLE_LONG" Fatal Error", MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2);
	if (ret == IDYES)
		Com_UploadCrashDump(dumpFile);

	return 0;
}
Ejemplo n.º 17
0
int main (int argc, char** argv) {
  if (argc < 2)
    exit(1);
  const char* fn=argv[1];
  fprintf(stderr,"file is %s\n",fn);
  bfd_init();
  bfd* bfd = bfd_openr(fn, NULL);
  if (bfd==NULL)
    exit(1);
  if (!bfd_check_format(bfd,bfd_object))
    exit(1);
  asection* s = bfd_get_section_by_name(bfd,".text");
  if (s==NULL)
    exit(1);
  unsigned char* blob;
  bfd_size_type sz = s->size;
  fprintf(stderr,".text is %zu bytes\n",sz);
  if(!bfd_malloc_and_get_section(bfd,s,&blob))
    exit(1);

  DISASM disObj;
  DISASM* dis = &disObj;
  memset(dis,0,sizeof(DISASM));

  unsigned int len;
  unsigned char* blobb = blob;
  unsigned int invalid = 0;
  unsigned int n = 0;
  dis->Archi = 64;
  do {
    dis->EIP = (UIntPtr)blobb;
    dis->SecurityBlock = sz; 
    len = Disasm(dis);
    if (len==OUT_OF_BLOCK) {
      fprintf(stderr,"out-of-block-error");
      exit(1);
    } else if (len==UNKNOWN_OPCODE) {
      invalid++;
      len = 1;
    } //else {
      //puts(dis->CompleteInstr);
    //}
    blobb += len;
    sz-=len;
    n++;
  } while(len > 0 && sz > 0);
  fprintf(stderr,"decoded %u opcode sequences (%u invalid/unknown)\n", n, invalid);
  return (0);
}
Ejemplo n.º 18
0
int main(int argc, char* argv[]) {


	bfd *obj, *objout;
	bfd_init();
	unsigned int h;


	if (argc != 2) {

		printf("not enough arguments!\n");
	}


	else {

		// printf("%s\n", argv[1]);


		obj = bfd_openr(argv[1], "elf64-x86-64");

		if (!obj) {

			bfd_perror("open failure\n");
		}

		if (!bfd_check_format(obj, bfd_object)) {

			printf("format error!\n");

		}

		else {


			// findSections passes findSectionData to map_over_sections
			findSections(obj, findSectionData);

		}

	}

	return 0;


}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
Archivo: naev.c Proyecto: ekrumme/naev
/**
 * @brief Sets up the SignalHandler for Linux.
 */
static void debug_sigInit( void )
{
#if HAS_LINUX && defined(DEBUGGING)
   char **matching;
   struct sigaction sa, so;

   bfd_init();

   /* Read the executable */
   abfd = bfd_openr("/proc/self/exe", NULL);
   if (abfd != NULL) {
      bfd_check_format_matches(abfd, bfd_object, &matching);

      /* Read symbols */
      if (bfd_get_file_flags(abfd) & HAS_SYMS) {
         long symcount;
         unsigned int size;

         /* static */
         symcount = bfd_read_minisymbols (abfd, FALSE, (void **)&syms, &size);
         if (symcount == 0) /* dynamic */
            symcount = bfd_read_minisymbols (abfd, TRUE, (void **)&syms, &size);
         assert(symcount >= 0);
      }
   }

   /* Set up handler. */
   sa.sa_handler   = NULL;
   sa.sa_sigaction = debug_sigHandler;
   sigemptyset(&sa.sa_mask);
   sa.sa_flags     = SA_SIGINFO;

   /* Attach signals. */
   sigaction(SIGSEGV, &sa, &so);
   if (so.sa_handler == SIG_IGN)
      DEBUG("Unable to set up SIGSEGV signal handler.");
   sigaction(SIGFPE, &sa, &so);
   if (so.sa_handler == SIG_IGN)
      DEBUG("Unable to set up SIGFPE signal handler.");
   sigaction(SIGABRT, &sa, &so);
   if (so.sa_handler == SIG_IGN)
      DEBUG("Unable to set up SIGABRT signal handler.");
#else /* HAS_LINUX && defined(DEBUGGING) */
   (void) executable;
#endif /* HAS_LINUX && defined(DEBUGGING) */
}
Ejemplo n.º 21
0
static int
init_bfd_ctx(struct bfd_ctx *bc, struct output_buffer *ob)
{
	bc->handle = NULL;
	bc->symbol = NULL;

	char procname[MAX_PATH];
	GetModuleFileNameA(NULL, procname, sizeof procname);

	bfd_init();
	bfd *b = bfd_openr(procname, 0);
	if (!b) {
		output_print(ob,"Failed to init bfd\n");
		return 1;
	}

	int r1 = bfd_check_format(b, bfd_object);
	int r2 = bfd_check_format_matches(b, bfd_object, NULL);
	int r3 = bfd_get_file_flags(b) & HAS_SYMS;

	if (!(r1 && r2 && r3)) {
		bfd_close(b);
		output_print(ob,"Failed to init bfd\n");
		return 1;
	}

	void *symbol_table;

	unsigned dummy = 0;
	if (bfd_read_minisymbols(b, FALSE, &symbol_table, &dummy) == 0) {
		if (bfd_read_minisymbols(b, TRUE, &symbol_table, &dummy) < 0) {
			free(symbol_table);
			bfd_close(b);
			output_print(ob,"Failed to init bfd\n");
			return 1;
		}
	}

	bc->handle = b;
	bc->symbol = symbol_table;

	return 0;
}
Ejemplo n.º 22
0
void ExchndlSetup(const char *packageVersion)
{
# if defined(WZ_CC_MINGW)
	wchar_t miniDumpPath[PATH_MAX] = {'\0'};

#ifdef HAVE_BFD
	bfd_init();
#endif /* HAVE_BFD */

	// Install the unhandled exception filter function
	prevExceptionFilter = SetUnhandledExceptionFilter(TopLevelExceptionFilter);

	// Retrieve the current version
	formattedVersionString = strdup(packageVersion);

	// Because of UAC on vista / win7 we use this to write our dumps to (unless we override it via OverrideRPTDirectory())
	// NOTE: CSIDL_PERSONAL =  C:\Users\user name\Documents
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, miniDumpPath ) ))
	{
		PathAppendW( miniDumpPath, WSTRING(WZ_WRITEDIR));
		PathAppendW( miniDumpPath, L"\\logs" );

		if( !PathFileExistsW( miniDumpPath ) )
		{
			if( ERROR_SUCCESS != SHCreateDirectoryExW( NULL, miniDumpPath, NULL ) )
			{
				wcscpy(miniDumpPath, L"c:\\temp");
			}
		}
	}
	else
	{	// should never fail, but if it does, we fall back to this
		wcscpy(miniDumpPath, L"c:\\temp");
	}

	wcscat(szLogFileName, L"Warzone2100.RPT");
	wcscat(miniDumpPath, L"\\");
	wcscat(miniDumpPath,szLogFileName);
	wcscpy(szLogFileName, miniDumpPath);

	atexit(ExchndlShutdown);
#endif
}
Ejemplo n.º 23
0
void arch_bfdResolveSyms(pid_t pid, funcs_t * funcs, size_t num)
{
    /* Guess what? libbfd is not multi-threading safe */
    while (pthread_mutex_lock(&arch_bfd_mutex)) ;

    bfd_init();

    bfd_t bfdParams = {
        .bfdh = NULL,
        .section = NULL,
        .syms = NULL,
    };

    if (arch_bfdInit(pid, &bfdParams) == false) {
        goto out;
    }

    const char *func;
    const char *file;
    unsigned int line;
    for (unsigned int i = 0; i < num; i++) {
        snprintf(funcs[i].func, sizeof(funcs->func), "[UNKNOWN]");
        if (funcs[i].pc == NULL) {
            continue;
        }
        long offset = (long)funcs[i].pc - bfdParams.section->vma;
        if ((offset < 0 || (unsigned long)offset > bfdParams.section->size)) {
            continue;
        }
        if (bfd_find_nearest_line
            (bfdParams.bfdh, bfdParams.section, bfdParams.syms, offset, &file, &func, &line)) {
            snprintf(funcs[i].func, sizeof(funcs->func), "%s", func);
            funcs[i].line = line;
        }
    }

 out:
    arch_bfdDestroy(&bfdParams);

    while (pthread_mutex_unlock(&arch_bfd_mutex)) ;
    return;
}
Ejemplo n.º 24
0
/// Initializes the loader of executable files by creating the corresponding bfd
/// image of the executable file specified as parameter.
trap::ExecLoader::ExecLoader(std::string filename, bool plain_file) : plain_file(plain_file) {
  this->program_data = NULL;
  this->exec_image = NULL;
  this->program_dim = 0;
  this->data_start = 0;
  char** matching = NULL;
  if (plain_file) {
    /// Read the input file, putting all the bytes of its content in the
    /// program_data array.
    boost::filesystem::path file_path = boost::filesystem::system_complete(boost::filesystem::path(filename));
    if (!boost::filesystem::exists(file_path)) {
      THROW_EXCEPTION("Path " << filename << " specified in the executable loader does not exist.");
    }
    std::ifstream plain_exec_file  ile(filename.c_str(), std::ifstream::in | std::ifstream::binary);
    if (!plain_exec_file.good())
      THROW_EXCEPTION("Cannot open file " << filename << '.');

    // Determine the size of the program being loaded.
    plain_exec_file.seekg (0, std::ios::end);
    this->program_dim = plain_exec_file.tellg();
    plain_exec_file.seekg (0, std::ios::beg);
    this->program_data = new unsigned char[this->program_dim];
    // Read the whole file
    plain_exec_file.read((char*)this->program_data, this->program_dim);
    this->data_start = 0;
    plain_exec_file.close();
  } else {
    bfd_init();
    this->exec_image = bfd_openr(filename.c_str(), "default");
    if (this->exec_image == NULL) {
      THROW_ERROR("Cannot open input file " << filename << ": " << bfd_errmsg(bfd_get_error()) << '.');
    }
    if (bfd_check_format (this->exec_image, bfd_archive)) {
      THROW_ERROR("Invalid input file " << filename << ", expected executable file, not archive.");
    }
    if (!bfd_check_format_matches (this->exec_image, bfd_object, &matching)) {
      THROW_ERROR("Invalid input file " << filename << ", the input file is not an object file or the target is ambiguous: " << this->get_matching_formats(matching) << '.');
    }
    this->load_program_data();
  }
} // ExecLoader::ExecLoader()
Ejemplo n.º 25
0
// --------------------------------------------------------------------------
bool ctkBinaryFileDescriptor::load()
{
  Q_D(ctkBinaryFileDescriptor);
  
  bfd_init();
  bfd * abfd = bfd_openr(d->FileName.toLatin1(), NULL);
  if (!abfd)
    {
    return false;
    }
  
  /* make sure it's an object file */
  if (!bfd_check_format (abfd, bfd_object)) 
    {
    bfd_close(abfd);
    return false;
    }
  
  d->BFD = abfd;
  return true;
}
Ejemplo n.º 26
0
/* initialize bincode */
bincode_t *initialize_bincode(const char *file)
{
    bfd *abfd;
    bincode_t *bin;
    //char *target = "x86_64-unknown-linux-gnu";
    char *target = "i686-pc-linux-gnu";

    bfd_init();

    if (!bfd_set_default_target(target)) {
        bs_dbgmsg("  (!) bfd_set_default_target()\n");
        return NULL;
    }

    if ((abfd = bfd_openr(file, target)) == NULL) {
        bs_dbgmsg("  (!) bfd_openr(): %s\n", file);
        return NULL;
    }

    if (!bfd_check_format(abfd, bfd_object)) {
        bs_dbgmsg("  (!) bfd_check_format()\n");
        bfd_close(abfd);
        return NULL;
    }

    if((bin = malloc(sizeof(bincode_t))) == NULL) {
        bs_errmsg("  (!) malloc(): bin\n");
        exit(EXIT_FAILURE);
    }

    bin->filename = strdup(abfd->filename);
    bin->abfd = abfd;
    bin->filesize = bfd_get_size(abfd);
    bin->start_addr = bfd_get_start_address(abfd);
    init_disasm_info(bin->abfd, &bin->disasm_info);
    bin->disasm_info.application_data = bin;
    initialize_section(bin);

    return bin;
}
Ejemplo n.º 27
0
static int is_bfd_symbols_available(void) {
	char name_buf[PATH_MAX];
	int n = readlink("/proc/self/exe", name_buf, sizeof(name_buf) - 1);
	if (n < 1)
		return 0;

	bfd *abfd;
	char** matching;

	bfd_init();
	name_buf[n] = 0;
	abfd = bfd_openr(name_buf, NULL);
	if (! abfd)
		return 0;

	n = 0;
	if ((bfd_get_file_flags(abfd) & HAS_SYMS) != 0
			&& bfd_check_format_matches(abfd, bfd_object, &matching))
		n = bfd_get_symtab_upper_bound(abfd) > 0;
	bfd_close(abfd);
	return n;
}
Ejemplo n.º 28
0
// Define BFD-related global variables.
static int define_bfd_vars(void)
{
	bfd * bfd;
	bfd_boolean r;
	int len;
#define MAX_PATHLENGTH 2048
	char mypath[MAX_PATHLENGTH];
     
	len = readlink("/proc/self/exe", mypath, sizeof(mypath));
     
	if (len < 0) {
		fprintf(stderr, "libopagent: readlink /proc/self/exe failed\n");
		return -1;
	}
	if (len >= MAX_PATHLENGTH) {
		fprintf(stderr, "libopagent: readlink /proc/self/exe returned"
			" path length longer than %d.\n", MAX_PATHLENGTH);

		return -1;
	}
	mypath[len] = '\0';

	bfd_init();
	bfd = bfd_openr(mypath, NULL);
	if (bfd == NULL) {
		bfd_perror("bfd_openr error. Cannot get required BFD info");
		return -1;
	}
	r = bfd_check_format(bfd, bfd_object);
	if (!r) {
		bfd_perror("bfd_get_arch error. Cannot get required BFD info");
		return -1;
	}
	_bfd_target_name =  bfd->xvec->name;
	_bfd_arch = bfd_get_arch(bfd);
	_bfd_mach = bfd_get_mach(bfd);

	return 0;
}
Ejemplo n.º 29
0
bfd *
initialize_bfd(const char *filename)
{
  bfd * abfd;
  char **matching;
  char *target = "i686-pc-linux-gnu";

  bfd_init();

  if(!bfd_set_default_target(target))
    fatal("program::initialize", "couldn't set default bfd target");
  
  abfd = bfd_openr(filename, target);
  if(abfd == NULL)
    fatal("initialize_bfd", "cannot open %s", filename);

  if (bfd_check_format (abfd, bfd_archive))
      fatal("initalize_bfd", "archive files  not supported\n");

  if(!bfd_check_format_matches(abfd, bfd_object, &matching))
    fatal("initialize_bfd", "bfd_check_format_matches failed");
  return abfd;
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
{
   if (argc <= 1)
   {
      fprintf(stderr, "Usage: %s <filename> <var1> <var2>\n\n", argv[0]);
      fprintf(stderr, "Where var1/var2 are variables in the program\n");
      fprintf(stderr, "E.g.: %s ./%s main abfd\n", argv[0], argv[0]);

      exit(ERROR); 
   }

   bfd_init();
   bfd_set_error_handler((bfd_error_handler_type)bfderror);

   abfd = bfd_openr(argv[1], NULL);

   if (abfd == NULL)
   {
      bfderror("[bfd_openr] error with opening %s", argv[1]);
      exit(ERROR);
   }

   setup(), showStats();

   printf("\nHit enter to continue..."), (void)getchar();

   dumpsects(bfd_get_section_by_name(abfd, ".text"));
   dumpsects(bfd_get_section_by_name(abfd, ".plt"));

   dumpsects(bfd_get_section_by_name(abfd, ".data"));
   dumpsects(bfd_get_section_by_name(abfd, ".bss"));

   getSyms(argv[2], argv[3]);

   bfd_close(abfd);
   return 0;
}