示例#1
0
文件: struct.c 项目: Gwaltrip/CLP
void print_structs(FILE* f, int d) {
	struct_table *curr = structs;
	while (curr != NULL) {
		fprintf(f, "struct: %s\n", curr->name);
		print_symbols(curr->s, f, 1);
		curr = curr -> next;
	}
}
示例#2
0
int main(int argc, char **argv)
{
	assert(argc > 1); 
	
	char *filename = argv[1];
	
	if (elf_version(EV_CURRENT) == EV_NONE ) {
		/* library out of date */
		fprintf(stderr, "Elf library out of date!n");
		exit(-1);
	}

	int fd = open(argv[1], O_RDONLY);

	if ((elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL){
        	 /*error*/
	}  

	check_symbol_table() && print_symbols(elf, symtab_section, &symtab_shdr);

}
示例#3
0
文件: main.c 项目: aeddi/nmotool
static int	nm(char *filename, t_arg_nm *options, t_bin *binary, size_t count)
{
	t_head	headers;

	get_binary_headers(binary->data, &headers);
	if (!headers.mach32 && !headers.mach64)
	{
		print_file_error(filename,
				"The file was not recognized as a valid object file.");
		return (1);
	}
	if ((!headers.mach32 && options->arch == A_X32) ||
		(!headers.mach64 && options->arch == A_X64))
		print_file_error(filename, "No architecture specified.");
	else if (((options->arch == A_ALL && (!headers.mach32 || !headers.mach64))
		|| options->arch == A_DEF ||
		(options->arch == A_X32 && headers.mach32 && !headers.mach64) ||
		(options->arch == A_X64 && headers.mach64 && !headers.mach32))
		&& count > 1
		&& !(options->arch == A_DEF && headers.mach32 && headers.mach64))
		print_filename_arch(filename, NULL);
	print_symbols(filename, options, &headers);
	return (0);
}
示例#4
0
/*
 * nm() is the routine that gets called by ofile_process() to process single
 * object files.
 */
static
void
nm(
struct ofile *ofile,
char *arch_name,
void *cookie)
{
    struct cmd_flags *cmd_flags;
    struct process_flags process_flags;
    unsigned long i, j, k;
    struct load_command *lc;
    struct symtab_command *st;
    struct dysymtab_command *dyst;
    struct segment_command *sg;
    struct section *s;

    struct nlist *symbols;
    unsigned long nsymbols;

	cmd_flags = (struct cmd_flags *)cookie;

	process_flags.nsect = -1;
	process_flags.sect_addr = 0;
	process_flags.sect_size = 0;
	process_flags.sect_start_symbol = FALSE;
	process_flags.nsects = 0;
	process_flags.sections = NULL;
	process_flags.text_nsect = NO_SECT;
	process_flags.data_nsect = NO_SECT;
	process_flags.bss_nsect = NO_SECT;

	st = NULL;
	dyst = NULL;
	lc = ofile->load_commands;
	for(i = 0; i < ofile->mh->ncmds; i++){
	    if(st == NULL && lc->cmd == LC_SYMTAB){
		st = (struct symtab_command *)lc;
	    }
	    else if(dyst == NULL && lc->cmd == LC_DYSYMTAB){
		dyst = (struct dysymtab_command *)lc;
	    }
	    else if(lc->cmd == LC_SEGMENT){
		sg = (struct segment_command *)lc;
		process_flags.nsects += sg->nsects;
	    }
	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
	}
	if(st == NULL || st->nsyms == 0){
	    error("no name list");
	    return;
	}
	if(process_flags.nsects > 0){
	    process_flags.sections = (struct section **)
		       malloc(sizeof(struct section *) * process_flags.nsects);
	    k = 0;
	    lc = ofile->load_commands;
	    for (i = 0; i < ofile->mh->ncmds; i++){
		if(lc->cmd == LC_SEGMENT){
		    sg = (struct segment_command *)lc;
		    s = (struct section *)
			  ((char *)sg + sizeof(struct segment_command));
		    for(j = 0; j < sg->nsects; j++){
			if(strcmp((s + j)->sectname, SECT_TEXT) == 0 &&
			   strcmp((s + j)->segname, SEG_TEXT) == 0)
			    process_flags.text_nsect = k + 1;
			else if(strcmp((s + j)->sectname, SECT_DATA) == 0 &&
				strcmp((s + j)->segname, SEG_DATA) == 0)
			    process_flags.data_nsect = k + 1;
			else if(strcmp((s + j)->sectname, SECT_BSS) == 0 &&
				strcmp((s + j)->segname, SEG_DATA) == 0)
			    process_flags.bss_nsect = k + 1;
			process_flags.sections[k++] = s + j;
		    }
		}
		lc = (struct load_command *)
		      ((char *)lc + lc->cmdsize);
	    }
	}

	/* select symbols to print */
	symbols = select_symbols(ofile, st, dyst, cmd_flags, &process_flags,
				 &nsymbols);

	/* set names in the symbols to be printed */
	strings = ofile->object_addr + st->stroff;
	strsize = st->strsize;

	    for(i = 0; i < nsymbols; i++){
		if(symbols[i].n_un.n_strx == 0)
		    symbols[i].n_un.n_name = "";
		else if(symbols[i].n_un.n_strx < 0 ||
			(unsigned long)symbols[i].n_un.n_strx > st->strsize)
		    symbols[i].n_un.n_name = "bad string index";
		else
		    symbols[i].n_un.n_name = symbols[i].n_un.n_strx + strings;

		if((symbols[i].n_type & N_TYPE) == N_INDR){
		    if(symbols[i].n_value == 0)
			symbols[i].n_value = (long)"";
		    else if(symbols[i].n_value > st->strsize)
			symbols[i].n_value = (long)"bad string index";
		    else
			symbols[i].n_value =
				    (long)(symbols[i].n_value + strings);
		}
	    }

	/* sort the symbols if needed */
	qsort(symbols, nsymbols, sizeof(struct nlist),
		(int (*)(const void *, const void *))compare);

	if (cmd_flags->c == TRUE) {
	    /* print header */
	    fprintf(output, "#ifndef _%s.H_\n", cmd_flags->ofile_name);
	    fprintf(output, "#define _%s.H_\n", cmd_flags->ofile_name);
	}
	
	/* now print the symbols as specified by the flags */
	print_symbols(ofile, symbols, nsymbols, strings, st->strsize,
			cmd_flags, &process_flags, arch_name);

	free(symbols);
	if(process_flags.sections != NULL)
	    free(process_flags.sections);
	    
	if (cmd_flags->c == TRUE) {
	    /* print footer */
	    fprintf(output, "#endif /* _%s.H_ */\n", cmd_flags->ofile_name);
	}
}
/* Main entry point of elf-parser */
int32_t main(int32_t argc, char *argv[])
{

	int32_t fd;
	Elf32_Ehdr eh;		/* elf-header is fixed size */

	if(argc!=2) {
		printf("Usage: elf-parser <ELF-file>\n");
		return 0;
	}

	fd = open(argv[1], O_RDONLY|O_SYNC);
	if(fd<0) {
		printf("Error %d Unable to open %s\n", fd, argv[1]);
		return 0;
	}

	/* ELF header : at start of file */
	read_elf_header(fd, &eh);
	if(!is_ELF(eh)) {
		return 0;
	}
	if(is64Bit(eh)){
		Elf64_Ehdr eh64;	/* elf-header is fixed size */
		Elf64_Shdr* sh_tbl;	/* section-header table is variable size */

		read_elf_header64(fd, &eh64);
		print_elf_header64(eh64);

		/* Section header table :  */
		sh_tbl = malloc(eh64.e_shentsize * eh64.e_shnum);
		if(!sh_tbl) {
			printf("Failed to allocate %d bytes\n",
					(eh64.e_shentsize * eh64.e_shnum));
		}
		read_section_header_table64(fd, eh64, sh_tbl);
		print_section_headers64(fd, eh64, sh_tbl);

		/* Symbol tables :
		 * sh_tbl[i].sh_type
		 * |`- SHT_SYMTAB
		 *  `- SHT_DYNSYM
		 */
		print_symbols64(fd, eh64, sh_tbl);

		/* Save .text section as text.S
		*/
		save_text_section64(fd, eh64, sh_tbl);

		/* Disassemble .text section
		 * Logs asm instructions to stdout
		 * Currently supports ARMv7
		 */
		disassemble64(fd, eh64, sh_tbl);

	} else{
		Elf32_Shdr* sh_tbl;	/* section-header table is variable size */
		print_elf_header(eh);

		/* Section header table :  */
		sh_tbl = malloc(eh.e_shentsize * eh.e_shnum);
		if(!sh_tbl) {
			printf("Failed to allocate %d bytes\n",
					(eh.e_shentsize * eh.e_shnum));
		}
		read_section_header_table(fd, eh, sh_tbl);
		print_section_headers(fd, eh, sh_tbl);

		/* Symbol tables :
		 * sh_tbl[i].sh_type
		 * |`- SHT_SYMTAB
		 *  `- SHT_DYNSYM
		 */
		print_symbols(fd, eh, sh_tbl);

		/* Save .text section as text.S
		*/
		save_text_section(fd, eh, sh_tbl);

		/* Disassemble .text section
		 * Logs asm instructions to stdout
		 * Currently supports ARMv7
		 */
		disassemble(fd, eh, sh_tbl);
	}

	return 0;

}
示例#6
0
/*
 * Copy a contents of binary file to the device.
 */
void write_image(const char *filename, const char *device_name, int verify_only)
{
    char buf[32*1024];
    int src, dest, n, progress_len, progress_step;
    struct stat st;
    off_t nbytes, count;
    struct timeval t0;

    src = open(filename, O_RDONLY);
    if (src < 0) {
        perror(filename);
        quit(0);
    }
    dest = open(device_name, O_RDWR);
    if (dest < 0) {
        perror(device_name);
        quit(0);
    }
    fstat(src, &st);
    nbytes = st.st_size;
    printf("     Source: %s\n", filename);
    printf("Destination: %s\n", device_name);
    printf("       Size: %.1f MB\n", nbytes / 1000000.0);

    /* Compute length of progress indicator. */
    for (progress_step=1; ; progress_step<<=1) {
        progress_len = (nbytes + sizeof(buf) - 1) / sizeof(buf);
        if (progress_len / progress_step < 64) {
            progress_len += progress_step - 1;
            progress_len /= progress_step;
            break;
        }
    }

    progress_count = 0;
    gettimeofday(&t0, 0);
    if (! verify_only) {
        printf("      Write: ");
        print_symbols('.', progress_len);
        print_symbols('\b', progress_len);
        fflush(stdout);
        for (count=0; count<nbytes; count+=sizeof(buf)) {
            /* Flush buffers every 4 Mbytes. */
            if (count % (4*1024*1024) == 0)
                fsync(dest);

            /* Read data into buffer. */
            n = nbytes - count;
            if (n > sizeof(buf))
                n = sizeof(buf);
            if (read(src, buf, n) != n) {
                fprintf(stderr, "%s: Read error\n", filename);
                quit(0);
            }

            /* Write data to the disk. */
            if (write(dest, buf, n) != n) {
                fprintf(stderr, "%s: Write error\n", device_name);
                quit(0);
            }
            progress(progress_step);
        }
        printf(" done      \n");
        fsync(dest);
    }
    if (verify_only) {
        char buf2[sizeof(buf)];

        printf("     Verify: ");
        print_symbols('.', progress_len);
        print_symbols('\b', progress_len);
        fflush(stdout);
        for (count=0; count<nbytes; count+=sizeof(buf)) {
            /* Read source data. */
            n = nbytes - count;
            if (n > sizeof(buf))
                n = sizeof(buf);
            if (read(src, buf, n) != n) {
                fprintf(stderr, "%s: Read error\n", filename);
                quit(0);
            }

            /* Read destination data. */
            if (read(dest, buf2, n) != n) {
                fprintf(stderr, "%s: Read error\n", device_name);
                quit(0);
            }

            /* Compare. */
            if (memcmp(buf, buf2, n) != 0) {
                fprintf(stderr, "DATA ERROR!\n");
                print_mismatch(buf, buf2, n,
                    lseek(src, 0, SEEK_CUR) - n);
                quit(0);
            }
            progress(progress_step);
        }
        printf(" done       \n");
    }
    close(src);
    close(dest);
    printf("      Speed: %.1f MB/sec\n",
        nbytes / 1000.0 / mseconds_elapsed(&t0));
}
示例#7
0
文件: main.c 项目: Gwaltrip/CLP
int main(int argc, char *argv[]) {

	/* process arguments */
	handle_opts(argc, argv);	

	/* open files */
	vlog("[plpcc] opening files\n");
	FILE_INPUT = fopen(S_FILE_INPUT,"r");
	if (FILE_INPUT == NULL) {
		err("[plpcc] cannot open input file: %s\n", S_FILE_INPUT);
	}
	FILE_OUTPUT = fopen(S_FILE_OUTPUT,"w");
	if (FILE_OUTPUT == NULL) {
		err("[plpcc] cannot open output file: %s\n", S_FILE_OUTPUT);
	}
	yyset_in(FILE_INPUT);

	if (S_SYMBOL_OUTPUT != NULL) {
		SYMBOL_OUTPUT = fopen(S_SYMBOL_OUTPUT, "w");
		if (SYMBOL_OUTPUT == NULL) {
			err("[plpcc] cannot open symbol table output file: %s\n", S_SYMBOL_OUTPUT);
		}
	}

	if (S_PARSE_OUTPUT != NULL) {
		PARSE_OUTPUT = fopen(S_PARSE_OUTPUT, "w");
		if (PARSE_OUTPUT == NULL) {
			err("[plpcc] cannot open parse tree output file: %s\n", S_PARSE_OUTPUT);
		}
	}
	
	if (S_GRAPH_OUTPUT != NULL) {
		GRAPH_OUTPUT = fopen(S_GRAPH_OUTPUT, "w");
		if (GRAPH_OUTPUT == NULL) {
			err("[plpcc] cannot open parse tree graph output file: %s\n", S_GRAPH_OUTPUT);
		}
	}

	/* grab the lines from the source for error handling and annotation */
	build_lines(S_FILE_INPUT);

	/* create an empty symbol table */
	sym = new_symbol_table(NULL);

	log("[plpcc] starting frontend\n");
	yyparse();

	/* print the parse tree */
	if (PARSE_OUTPUT != NULL) {
		vlog("[plpcc] printing parse tree\n");
		print_tree(parse_tree_head, PARSE_OUTPUT, 0);
	}

	/* print the parse tree graph formatted for Graphviz*/
	if (GRAPH_OUTPUT != NULL) {
		vlog("[plpcc] printing parse tree graph\n");
		print_tree_graph(parse_tree_head, GRAPH_OUTPUT, S_FILE_INPUT);
		
		/* close output file*/
		fclose(GRAPH_OUTPUT);
		
		/* Run Graphviz command to generate PNG of parse tree */
		S_GRAPH_COMMAND = malloc(sizeof(char) * (strlen(S_FILE_OUTPUT) * 2 + 22));
		sprintf(S_GRAPH_COMMAND, "dot -Tpng %s.dot > %s.png", S_FILE_OUTPUT, S_FILE_OUTPUT);
		system(S_GRAPH_COMMAND);
	}
	
	/* print the symbol table */
	if (SYMBOL_OUTPUT != NULL) {
		vlog("[plpcc] printing symbol table\n");
		print_symbols(sym, SYMBOL_OUTPUT, 0);
		vlog("[plpcc] printing activation records\n");
		print_frames(sym, SYMBOL_OUTPUT);
	}

	/* call the backend to compile the parse tree, starting from the head */
	if (NO_COMPILE == 0) {
		handle(parse_tree_head);
		fprintf(FILE_OUTPUT, "%s", program);
	}

	vlog("[plpcc] closing files\n");
	fclose(FILE_INPUT);
	fclose(FILE_OUTPUT);

	log("[plpcc] done\n");
	return 0;
}
示例#8
0
文件: main.c 项目: KurSh/crxprof
int
main(int argc, char *argv[])
{
    bool need_exit = false;
    ptrace_context ptrace_ctx;
    program_params params;
    struct itimerval itv;
    struct proc_timer proc_time;
    calltree_node *root = NULL;

    g_progname = argv[0];
    if (!parse_args(&params, argc, argv))
        usage();

    print_message("Reading symbols (list of function)");
    init_fndescr(params.pid);
    if (params.just_print_symbols) {
        print_symbols();
        free_fndescr();
        exit(0);
    }

    if (!reset_process_time(&proc_time, params.pid, params.prof_method)) {
        free_fndescr();
        errx(2, "Failed to retrieve process time");
    }


    print_message("Attaching to process: %d", params.pid);
    memset(&ptrace_ctx, 0, sizeof(ptrace_ctx));
    if (!trace_init(params.pid, &ptrace_ctx))
        err(1, "Failed to initialize unwind internals");

    signal(SIGCHLD, on_sigchld);
    if (ptrace(PTRACE_ATTACH, params.pid, 0, 0) == -1) {
        int saved_errno = errno;
        warn("ptrace(PTRACE_ATTACH) failed");
        if (saved_errno == EPERM) {
            printf("You have to see NOTES section of `man crxprof' for workarounds.\n");
        }
        exit(2);
    }

    if (do_wait(&ptrace_ctx, true) != WR_STOPPED)
        err(1, "Error occured while stopping the process");

    if (ptrace(PTRACE_CONT, params.pid, 0, 0) < 0)
        err(1, "Error occured while stopping the process 2");


    /* interval timer for snapshots */
    itv.it_interval.tv_sec = 0;
    itv.it_interval.tv_usec = params.us_sleep;
    itv.it_value = itv.it_interval;

    signal(SIGALRM, on_sigalarm);
    if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
        err(1, "setitimer failed");

    print_message("Starting profile (interval %dms)", params.us_sleep / 1000);
    print_message("Press ^C once to show profile, twice to quit");
    signal(SIGINT, on_sigint);

    /* drop first meter since it contains our preparations */
    (void)get_process_dt(&proc_time); 

    while(!need_exit)
    {
        waitres_t wres = WR_NOTHING;
        sleep(1);
        
        if (timer_alarmed) {
            uint64_t proc_dt = get_process_dt(&proc_time);
            bool need_prof = (params.prof_method == PROF_REALTIME);

            if (params.prof_method == PROF_CPUTIME) {
                char st = get_procstate(&ptrace_ctx);
                if (st == 'R')
                    need_prof = true;
            }

            if (need_prof) {
                kill(params.pid, SIGSTOP);
                wres = do_wait(&ptrace_ctx, true);
                if (wres == WR_STOPPED) {
                    int signo_cont = (ptrace_ctx.stop_signal == SIGSTOP) ? 0 : ptrace_ctx.stop_signal;

                    if (!get_backtrace(&ptrace_ctx))
                        err(2, "failed to get backtrace of process");

                    /* continue tracee ASAP */
                    if (ptrace_verbose(PTRACE_CONT, params.pid, 0, signo_cont) < 0)
                        err(1, "ptrace(PTRACE_CONT) failed");

                    ptrace_ctx.nsnaps++;
                    if (fill_backtrace(proc_dt, &ptrace_ctx.stk, &root))
                        ptrace_ctx.nsnaps_accounted++;
                }
            }
        }

        if (wres != WR_FINISHED && wres != WR_NEED_DETACH) {
            wres = discard_wait(&ptrace_ctx);
        }


        if (sigint_caught_twice) {
            need_exit = true;
        } else if (sigint_caught || wres == WR_FINISHED || wres == WR_NEED_DETACH) {
            if (root) {
                print_message("%" PRIu64 " snapshot interrputs got (%" PRIu64 " dropped)", 
                    ptrace_ctx.nsnaps, ptrace_ctx.nsnaps - ptrace_ctx.nsnaps_accounted);

                visualize_profile(root, &params.vprops);
                if (params.dumpfile)
                    dump_profile(root, params.dumpfile);
            } else
                print_message("No symbolic snapshot caught yet!");
    
            sigint_caught = false;
        }

        if (wres == WR_FINISHED || wres == WR_NEED_DETACH) {
            if (wres == WR_NEED_DETACH)
                (void)ptrace_verbose(PTRACE_DETACH, params.pid, 0, ptrace_ctx.stop_signal);

            need_exit = true;
        }
    }

    free_fndescr();
    trace_free(&ptrace_ctx);
    if (root)
        calltree_destroy(root);

    return 0;
}
示例#9
0
int main(int argc, char **argv){

	// perform sanity check on arguments
	if(argc < 3 || argc > 6){
		print_help(argv[0]);
		return 1;
	}

	// process argument options
	int c = 3;
	while(c < argc){
		if(strcmp(argv[c], WARN_FLAG) == 0)
			warnings = 1;
		else if(strcmp(argv[c], SYST_FLAG) == 0)
			print_tables = 1;
		else if(strcmp(argv[c], COMP_INFO) == 0)
			print_comp_i = 1;
		else if(strcmp(argv[c], HELP_FLAG) == 0)
			print_help(argv[0]);
		else if(strcmp(argv[c], FAST_FLAG) == 0)
			make_fast = 1;
		else{
			print_asterisk(RED_C, stderr);
			fprintf(stderr, "Unknown flag '%s'.\n\n", argv[c]);
			print_help(argv[0]);
			return 1;
		}
		c++;
	}

	// try to open/create the files the user wants us to use
	FILE *input_file = fopen(argv[1], "r");
	FILE *out_file = 0;

	if(!input_file){
		print_asterisk(RED_C, stderr);
		fprintf(stderr, "Error: Unable to open '%s' for "
		"reading, exiting.\n", argv[1]);
		return 2;
	}
	out_file = open_write_file(argv[2]);
	if(!out_file){
		print_asterisk(RED_C, stderr);
		fprintf(stderr, "Error: Unable to open '%s' for writing, exiting.\n",
				argv[2]);
		return 2;
	}

	// print banner
	if(print_comp_i){
		printf( "\t\t=== Hartz Translator ===\n"
				"Machine Constraints\n"
				"\t%d Bytes of Memory\n"
				"\t%d Registers\n"
				"\t%d Bytes of Cache\n\n"
				"Compiler Constraints\n"
				"\tMax Line Length of %d Bytes\n"
				"\tMax One Instruction Per Line\n\n",
				MAX_MEMORY, MAX_REGS, MAX_CACHE, MAX_LINE_LEN);
	}

	// setup our program struct to store some data
	struct program *program = (struct program*) malloc(sizeof(struct program));
	memset(program, 0, sizeof(struct program));
	program->out = out_file;
	program->input = argv[1];
	program->in = input_file;

	if(make_fast){
		write_instruc_str(HALT, 0, 0, 0, 0, program);
		fclose(input_file);
		fclose(out_file);
		return 0;
	}

	// create the symbol table
	struct symbol_table *tbl = (struct symbol_table*) malloc(
	sizeof(struct symbol_table));
	memset(tbl, 0, sizeof(struct symbol_table));
	program->tbl = tbl;

	// Create the table for constants
	struct symbol_table *const_tbl = (struct symbol_table*) malloc(
	sizeof(struct symbol_table));
	memset(const_tbl, 0, sizeof(struct symbol_table));
	program->const_tbl = const_tbl;

	// start processing file
	process_input_program(program);
	fclose(input_file);
	fclose(out_file);

	if(print_tables){
		printf("\n");
		print_symbols(program->tbl);
		print_symbols(program->const_tbl);
		printf("\n");
	}

	if(program->error_code){
		print_asterisk(RED_C, stderr);
		fprintf(stderr, "Stopped processing because of an error.\n");
	}
	else{
		print_asterisk(GRN_C, stdout);
		printf("Done!\n");
	}
}
示例#10
0
文件: buttons.c 项目: Bpara001/CS_UCR
static void
print_symbol_action (Widget w, XtPointer client_data, XtPointer call_data)
{
  print_symbols ();
}