int rawdump( int argc, char **argv ) { if (argc != 5) return Usage( 1 ); FILE *fp = fopen( argv[2], "rb" ); int hdrlen = atoi( argv[3] ); int reclen = atoi( argv[4] ); long int recnum = 0; if (!fp) return 1; if (hdrlen) { if (fread( buffer, hdrlen, 1, fp ) != 1) { return 1; } printf( "Header:\n" ); fdump( stdout, buffer, hdrlen ); } while (fread( buffer, reclen, 1, fp ) == 1) { printf( "Record %ld (%lx):\n", recnum, recnum ); fdump( stdout, buffer, reclen ); ++recnum; } printf( "%ld records read.\n",recnum ); return 0; }
int main(int argc, char* argv[]) { if (argc>2) { fdump(argv[1],argv[2]); } return 0; }
void handle_rename_char( Client* client, PKTIN_75* msg ) { Character* chr = find_character( cfBEu32( msg->serial )); if (chr != NULL) { if (client->chr->can_rename( chr )) { msg->name[ sizeof msg->name-1 ] = '\0'; // check for legal characters for( char* p = msg->name; *p; p++ ) { // only allow: a-z, A-Z & spaces if ( *p != ' ' && !isalpha(*p) ) { char buffer[512]; sprintf(buffer, "Client #%lu (account %s) attempted an invalid rename (packet 0x%2.02x):", client->instance_, (client->acct != NULL) ? client->acct->name() : "unknown", msg->msgtype); cout << buffer << endl; fdump( stdout, msg->name, static_cast<int>(strlen(msg->name)) ); if (logfile) { Log("%s\n", buffer); fdump( logfile, msg->name, static_cast<int>(strlen(msg->name)) ); } *p = '\0'; send_sysmessage( client, "Invalid name!" ); return; //dave 12/26 if invalid name, do not apply to chr! } } chr->setname( msg->name ); } else { send_sysmessage( client, "I can't rename that." ); } } else { send_sysmessage( client, "I can't find that." ); } }
void main(void) { Tree *t; File *hello, *goodbye, *world; t = mktree(); hello = fcreate(t->root, "hello", CHDIR|0777); assert(hello != nil); goodbye = fcreate(t->root, "goodbye", CHDIR|0777); assert(goodbye != nil); world = fcreate(hello, "world", 0666); assert(world != nil); world = fcreate(goodbye, "world", 0666); assert(world != nil); fdump(t->root, 0); fremove(world); fdump(t->root, 0); }
void dump_tList(FILE* fp, tList* pp) { if (fp==NULL) fp = stderr; if (pp!=NULL) { while(pp!=NULL) { tList_data ld = pp->ldat; fprintf(fp, "[%d] [%d] [%s] [%d]\n", ld.id, ld.lv, ld.key.buf, ld.val.vldsz); fdump(fp, (unsigned char*)ld.val.buf, ld.val.vldsz); pp = pp->next; } } else { fprintf(fp, "(List is NULL)\n"); } return; }
void dump_code(void) { fdump(); /* dumps all user functions */ if (begin_start) { fprintf(stdout, "BEGIN\n"); da(begin_start, stdout); } if (end_start) { fprintf(stdout, "END\n"); da(end_start, stdout); } if (main_start) { fprintf(stdout, "MAIN\n"); da(main_start, stdout); } }
int main(int argc, char* argv[]) { printf("/* code automatically generated by bin2c -- DO NOT EDIT */\n"); printf("{\n"); if (argc<2) { dump(stdin,0); emit("=stdin",0); } else { int i; printf("/* #include'ing this file in a C program is equivalent to calling\n"); for (i=1; i<argc; i++) printf(" lua_dofile(L,\"%s\");\n",argv[i]); printf("*/\n"); for (i=1; i<argc; i++) fdump(argv[i],i); for (i=1; i<argc; i++) emit(argv[i],i); } printf("}\n"); return 0; }
__inline void dump(const byte_t *data_buffer, const unsigned int length) { fdump(stdout, data_buffer, length); }
void CppCheck::checkFile(const std::string &code, const char FileName[]) { if (_settings.terminated() || _settings.checkConfiguration) return; Tokenizer _tokenizer(&_settings, this); if (_settings._showtime != SHOWTIME_NONE) _tokenizer.setTimerResults(&S_timerResults); try { bool result; // Execute rules for "raw" code for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) { if (it->tokenlist == "raw") { Tokenizer tokenizer2(&_settings, this); std::istringstream istr(code); tokenizer2.list.createTokens(istr, FileName); executeRules("raw", tokenizer2); break; } } // Tokenize the file std::istringstream istr(code); Timer timer("Tokenizer::tokenize", _settings._showtime, &S_timerResults); result = _tokenizer.tokenize(istr, FileName, cfg); timer.Stop(); if (!result) { // File had syntax errors, abort return; } // dump if (_settings.dump) { std::string dumpfile = std::string(FileName) + ".dump"; std::ofstream fdump(dumpfile.c_str()); if (fdump.is_open()) { fdump << "<?xml version=\"1.0\"?>" << std::endl; fdump << "<dump cfg=\"" << cfg << "\">" << std::endl; _tokenizer.dump(fdump); fdump << "</dump>" << std::endl; } return; } // call all "runChecks" in all registered Check classes for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { if (_settings.terminated()) return; Timer timerRunChecks((*it)->name() + "::runChecks", _settings._showtime, &S_timerResults); (*it)->runChecks(&_tokenizer, &_settings, this); } if (_settings.isEnabled("unusedFunction") && _settings._jobs == 1) CheckUnusedFunctions::instance.parseTokens(_tokenizer, FileName, &_settings); executeRules("normal", _tokenizer); if (!_simplify) return; Timer timer3("Tokenizer::simplifyTokenList2", _settings._showtime, &S_timerResults); result = _tokenizer.simplifyTokenList2(); timer3.Stop(); if (!result) return; // call all "runSimplifiedChecks" in all registered Check classes for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { if (_settings.terminated()) return; Timer timerSimpleChecks((*it)->name() + "::runSimplifiedChecks", _settings._showtime, &S_timerResults); (*it)->runSimplifiedChecks(&_tokenizer, &_settings, this); } if (_settings.terminated()) return; executeRules("simple", _tokenizer); if (_settings.terminated()) return; } catch (const InternalError &e) { std::list<ErrorLogger::ErrorMessage::FileLocation> locationList; ErrorLogger::ErrorMessage::FileLocation loc; if (e.token) { loc.line = e.token->linenr(); const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token)); loc.setfile(fixedpath); } else { ErrorLogger::ErrorMessage::FileLocation loc2; loc2.setfile(Path::toNativeSeparators(FileName)); locationList.push_back(loc2); loc.setfile(_tokenizer.list.getSourceFilePath()); } locationList.push_back(loc); const ErrorLogger::ErrorMessage errmsg(locationList, Severity::error, e.errorMessage, e.id, false); _errorLogger.reportErr(errmsg); } }
int listen_for_code(void){ int sockfd, new_sockfd, port=PORT, yes=1, recvlength=1; socklen_t sin_size; char buffer[TRANSMISSION_SIZE]; struct sockaddr_in srv_addr, cli_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) fatal("in socket"); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) fatal("setting socket option SO_REUSEADDR"); srv_addr.sin_family = AF_INET; // host byte order srv_addr.sin_port = htons(port); // short, network byte order srv_addr.sin_addr.s_addr = 0; // automatically fill with my ip address memset(&(srv_addr.sin_zero), '\0', 8); // zero out the rest of the struct if (bind(sockfd, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)) == -1) fatal("binding to socket"); if (listen(sockfd, 5) == -1) fatal("listening on socket"); /** * Main loop **/ unsigned char *codebuffer; unsigned char *result; char *sexp; int codelength, actual_sexp_length; codebuffer = malloc(MAX_CODE_SIZE); result = malloc(SYSREG_BYTES); sexp = malloc(SEXP_LENGTH); while (1) { sin_size = sizeof(struct sockaddr_in); if ((new_sockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &sin_size)) == -1) fatal("accepting connection"); printf("SERVER: ACCEPTED CONNECTION FROM %s PORT %d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port)); //send(new_sockfd, "Hello, world!\n\r", 13, 0); // just for testing recvlength = recv(new_sockfd, &buffer, TRANSMISSION_SIZE, 0); /** * Clean the buffers **/ memset(codebuffer, 0, MAX_CODE_SIZE); memset(result, 0, SYSREG_BYTES); memset(sexp, 0, SEXP_LENGTH); codelength = 0; while (recvlength > 0) { printf("RECV: %d bytes\n", recvlength); if (DUMP) fdump(stdout, buffer, recvlength); // memcpy(codebuffer+codelength, buffer, recvlength); codelength = codecopy(codebuffer, buffer, codelength, recvlength); // codelength += recvlength; printf("code length = %d\n", codelength); if (READY(codelength)){ hatch_code(codebuffer, NULL, result); actual_sexp_length = lisp_encode(result, sexp); send(new_sockfd, sexp, actual_sexp_length, 0); break; } else { recvlength = recv(new_sockfd, &buffer, TRANSMISSION_SIZE, 0); } } close(new_sockfd); } free(codebuffer); free(result); free(sexp); }
int main(int argc, char *argv[]) { int dummy, dummysigalrm, foreground = 0; struct timeval tv, difftime, curtime, lasttime, *timeout; fd_set rfds, readers; int nfds, n, i, secs, ch; struct sigaction sa; time_t boottime; struct option long_options[] = { {"config", 1, 0, 'c'}, {"debug", 2, 0, 'd'}, {"foreground", 0, 0, 'f'}, {"disable-vifs", 0, 0, 'N'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"quit-daemon", 0, 0, 'q'}, {"reload-config", 0, 0, 'l'}, {"show-routes", 0, 0, 'r'}, /* {"show-cache", 0, 0, 'i'}, */ /* {"show-debug", 0, 0, 'p'}, */ {0, 0, 0, 0} }; snprintf(versionstring, sizeof (versionstring), "pimd version %s", todaysversion); while ((ch = getopt_long (argc, argv, "c:d::fhlNP::vqr", long_options, NULL)) != EOF) { switch (ch) { case 'c': configfilename = optarg; break; case 'd': if (!optarg) { debug = DEBUG_DEFAULT; } else { char *p,*q; size_t i, len; struct debugname *d; debug = 0; p = optarg; q = NULL; while (p) { q = strchr(p, ','); if (q) *q++ = '\0'; len = strlen(p); for (i = 0, d = debugnames; i < ARRAY_LEN(debugnames); i++, d++) if (len >= d->nchars && strncmp(d->name, p, len) == 0) break; if (i == ARRAY_LEN(debugnames)) return usage(); debug |= d->level; p = q; } } break; case 'f': foreground = 1; break; case 'h': return usage(); case 'l': killshow(SIGHUP, NULL); return 0; case 'N': disable_all_by_default = 1; break; case 'P': #ifdef SNMP if (!optarg) dest_port = DEFAULT_PORT; else { dest_port = strtonum(optarg, 1, 65535, &errstr); if (errstr) { warnx("destination port %s", errstr); dest_port = DEFAULT_PORT; } } #else warnx("SNMP support missing, please feel free to submit a patch."); #endif break; case 'v': printf("%s\n", versionstring); return 0; case 'q': killshow(SIGTERM, NULL); return 0; case 'r': killshow(SIGUSR1, _PATH_PIMD_DUMP); return 0; #if 0 /* XXX: TODO */ case 'i': killshow(SIGUSR2, _PATH_PIMD_CACHE); return 0; case 'p': killshow(SIGQUIT, NULL); return 0; #endif default: return usage(); } } argc -= optind; argv += optind; if (argc > 0) { return usage(); } if (geteuid() != 0) { fprintf(stderr, "%s: must be root\n", __progname); exit(1); } setlinebuf(stderr); if (debug != 0) { struct debugname *d; char c; int tmpd = debug; fprintf(stderr, "debug level 0x%lx ", debug); c = '('; for (d = debugnames; d < debugnames + ARRAY_LEN(debugnames); d++) { if ((tmpd & d->level) == d->level) { tmpd &= ~d->level; fprintf(stderr, "%c%s", c, d->name); c = ','; } } fprintf(stderr, ")\n"); } /* * Create directory for runtime files */ mkdir(_PATH_PIMD_RUNDIR, 0755); /* * Setup logging */ #ifdef LOG_DAEMON (void)openlog("pimd", LOG_PID, LOG_DAEMON); (void)setlogmask(LOG_UPTO(LOG_NOTICE)); #else (void)openlog("pimd", LOG_PID); #endif /* LOG_DAEMON */ logit(LOG_DEBUG, 0, "%s starting", versionstring); do_randomize(); time(&boottime); /* Start up the log rate-limiter */ resetlogging(NULL); callout_init(); init_igmp(); init_pim(); #ifdef HAVE_ROUTING_SOCKETS init_routesock(); #endif /* HAVE_ROUTING_SOCKETS */ init_pim_mrt(); init_timers(); /* TODO: check the kernel DVMRP/MROUTED/PIM support version */ #ifdef SNMP if (i = snmp_init()) return i; #endif /* SNMP */ init_vifs(); init_rp_and_bsr(); /* Must be after init_vifs() */ #ifdef RSRR rsrr_init(); #endif /* RSRR */ sa.sa_handler = handler; sa.sa_flags = 0; /* Interrupt system calls */ sigemptyset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); FD_ZERO(&readers); FD_SET(igmp_socket, &readers); nfds = igmp_socket + 1; for (i = 0; i < nhandlers; i++) { FD_SET(ihandlers[i].fd, &readers); if (ihandlers[i].fd >= nfds) nfds = ihandlers[i].fd + 1; } IF_DEBUG(DEBUG_IF) dump_vifs(stderr); IF_DEBUG(DEBUG_PIM_MRT) dump_pim_mrt(stderr); /* schedule first timer interrupt */ timer_setTimer(TIMER_INTERVAL, timer, NULL); if (!debug && !foreground) { /* Detach from the terminal */ haveterminal = 0; if (fork()) exit(0); (void)close(0); (void)close(1); (void)close(2); (void)open("/", 0); (void)dup2(0, 1); (void)dup2(0, 2); #ifdef SYSV (void)setpgrp(); #else #ifdef TIOCNOTTY n = open("/dev/tty", 2); if (n >= 0) { (void)ioctl(n, TIOCNOTTY, (char *)0); (void)close(n); } #else if (setsid() < 0) perror("setsid"); #endif /* TIOCNOTTY */ #endif /* SYSV */ } /* End of child process code */ if (pidfile(NULL)) { warn("Cannot create pidfile"); } /* * Main receive loop. */ dummy = 0; dummysigalrm = SIGALRM; difftime.tv_usec = 0; gettimeofday(&curtime, NULL); lasttime = curtime; while (1) { memcpy(&rfds, &readers, sizeof(rfds)); secs = timer_nextTimer(); if (secs == -1) timeout = NULL; else { timeout = &tv; timeout->tv_sec = secs; timeout->tv_usec = 0; } if (boottime) { time_t n; time(&n); if (n > boottime + 15) { struct rp_hold *rph = g_rp_hold; while(rph) { add_rp_grp_entry(&cand_rp_list, &grp_mask_list, rph->address, 1, (u_int16)0xffffff, rph->group, rph->mask, curr_bsr_hash_mask, curr_bsr_fragment_tag); rph = rph->next; } boottime = 0; } } if (sighandled) { if (sighandled & GOT_SIGINT) { sighandled &= ~GOT_SIGINT; break; } if (sighandled & GOT_SIGHUP) { sighandled &= ~GOT_SIGHUP; restart(SIGHUP); /* reconstruct readers and nfds */ FD_ZERO(&readers); FD_SET(igmp_socket, &readers); nfds = igmp_socket + 1; for (i = 0; i < nhandlers; i++) { FD_SET(ihandlers[i].fd, &readers); if (ihandlers[i].fd >= nfds) nfds = ihandlers[i].fd + 1; } memcpy(&rfds, &readers, sizeof(rfds)); } if (sighandled & GOT_SIGUSR1) { sighandled &= ~GOT_SIGUSR1; fdump(SIGUSR1); } if (sighandled & GOT_SIGUSR2) { sighandled &= ~GOT_SIGUSR2; cdump(SIGUSR2); } if (sighandled & GOT_SIGALRM) { sighandled &= ~GOT_SIGALRM; timer(&dummysigalrm); } } if ((n = select(nfds, &rfds, NULL, NULL, timeout)) < 0) { if (errno != EINTR) /* SIGALRM is expected */ logit(LOG_WARNING, errno, "select failed"); continue; } if (n > 0) { /* TODO: shall check first igmp_socket for better performance? */ for (i = 0; i < nhandlers; i++) { if (FD_ISSET(ihandlers[i].fd, &rfds)) { (*ihandlers[i].func)(ihandlers[i].fd, &rfds); } } } /* * Handle timeout queue. * * If select + packet processing took more than 1 second, * or if there is a timeout pending, age the timeout queue. * * If not, collect usec in difftime to make sure that the * time doesn't drift too badly. * * If the timeout handlers took more than 1 second, * age the timeout queue again. XXX This introduces the * potential for infinite loops! */ do { /* * If the select timed out, then there's no other * activity to account for and we don't need to * call gettimeofday. */ if (n == 0) { curtime.tv_sec = lasttime.tv_sec + secs; curtime.tv_usec = lasttime.tv_usec; n = -1; /* don't do this next time through the loop */ } else gettimeofday(&curtime, NULL); difftime.tv_sec = curtime.tv_sec - lasttime.tv_sec; difftime.tv_usec += curtime.tv_usec - lasttime.tv_usec; while (difftime.tv_usec >= 1000000) { difftime.tv_sec++; difftime.tv_usec -= 1000000; } if (difftime.tv_usec < 0) { difftime.tv_sec--; difftime.tv_usec += 1000000; } lasttime = curtime; if (secs == 0 || difftime.tv_sec > 0) age_callout_queue(difftime.tv_sec); secs = -1; } while (difftime.tv_sec > 0); } /* Main loop */ logit(LOG_NOTICE, 0, "%s exiting", versionstring); cleanup(); exit(0); }
int main(int argc, char **argv){ fprintf(stderr,"NGSrelate buildtime: (%s:%s)\n",__DATE__,__TIME__); if(argc==1){// if no arguments, print info on program info(); return 0; } //below for catching ctrl+c, and dumping files struct sigaction sa; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = handler; sigaction(SIGPIPE, &sa, 0); sigaction(SIGINT, &sa, 0); //initial values char *bfile = NULL; char *binfile = NULL; char *outfiles = NULL; double a,k0,k1,k2; a=k0=k1=-1; k2=0; int calcA = 1; //filter opts double minMaf = 0.01; char *freqfile =NULL; // reading arguments argv++; while(*argv){ if(strcmp(*argv,"-beagle")==0 ) bfile=*++argv; else if(strcmp(*argv,"-bin")==0 ) binfile=*++argv; else if(strcmp(*argv,"-freqfile")==0 ) freqfile=*++argv; else if(strcmp(*argv,"-outnames")==0 ) outfiles=*++argv; else if(strcmp(*argv,"-minMaf")==0 ) minMaf = atoi(*++argv); else if(strcmp(*argv,"-a")==0 ) a = atof(*++argv); else if(strcmp(*argv,"-k0")==0 ) k0 = atof(*++argv); else if(strcmp(*argv,"-k1")==0 ) k1 = atof(*++argv); else if(strcmp(*argv,"-k2")==0 ) k2 = atof(*++argv); else if(strcmp(*argv,"-calcA")==0 ) calcA = atoi(*++argv); else{ fprintf(stderr,"Unknown arg:%s\n",*argv); info(); return 0; } ++argv; } if(bfile==NULL&&binfile==NULL){ fprintf(stderr,"Please supply input data file: -beagle OR -bin"); info(); }else if(bfile!=NULL&&binfile!=NULL){ fprintf(stderr,"Please supply input data file: -beagle OR -bin"); info(); } if(outfiles==NULL){ if(bfile!=NULL) outfiles=bfile; else outfiles = binfile; fprintf(stderr,"Will use: %s as prefix for output\n",outfiles); } FILE *flog=openFile(outfiles,".log"); clock_t t=clock();//how long time does the run take time_t t2=time(NULL); std::vector<perChr> pd; if(bfile!=NULL){ bgl d=readBeagle(bfile); fprintf(stderr,"Input beaglefile has dim: nsites=%d nind=%d\n",d.nSites,d.nInd); pd = makeDat(d); gzFile dfile = openFileGz(outfiles,".bin.gz","wb"); for(uint i=0;i<pd.size();i++) marshall_dump(dfile,pd[i]); gzclose(dfile); }else{ gzFile dfile = getGz(binfile,"rb"); pd = marshall_read(dfile); gzclose(dfile); } //calculate frequencies for(uint i=0;i<pd.size();i++) setFreq(pd[i]); // printStuff(pd); //set seed srand(seed); //below is the main looping trhought the iterations. FILE *fp =openFile(outfiles,".freq"); for(int i=0;i<pd[0].nSites;i++) fprintf(fp,"%f ",exp(pd[0].freq[i])); fclose(fp); double *freq = NULL; if(freqfile!=NULL){ freq = readDouble(freqfile,pd[0].nSites); fprintf(stderr,"freq=%f\n",freq[0]); } para p; p.pair[0] = 0;p.pair[1] = 1; p.a=a;p.k0=k0;p.k1=k1;p.k2=k2; fprintf(stderr,"pa=%f pk0=%f\n",p.a,p.k0); hmm res = analysis(pd[0],freq,p,calcA); gzFile bo = openFileGz(outfiles,".bres.gz","wb"); fdump(bo,res,pd[0].name); //deallocate memory for(int i=0;1&&i<dumpedFiles.size();i++){ fprintf(stderr,"dumpedfiles are: %s\n",dumpedFiles[i]); free(dumpedFiles[i]); } fprintf(stderr, "\t[ALL done] cpu-time used = %.2f sec\n", (float)(clock() - t) / CLOCKS_PER_SEC); fprintf(stderr, "\t[ALL done] walltime used = %.2f sec\n", (float)(time(NULL) - t2)); // print to log file fprintf(flog, "\t[ALL done] cpu-time used = %.2f sec\n", (float)(clock() - t) / CLOCKS_PER_SEC); fprintf(flog, "\t[ALL done] walltime used = %.2f sec\n", (float)(time(NULL) - t2)); fclose(flog); gzclose(bo); return 0; }
/** * This is the part that launches the code in the Unicorn emulator. **/ int em_code(u8 *code, u32 bytelength, u32 startat, u8 *seed_res, uc_arch arch){ // bit of lazy coding here: update a global arch var, so that // we can easily read the arch from the single step hook. // neither elegant nor dangerous. if (global_arch != arch) global_arch = arch; /* The start address must be aligned to 4KB, or uc_mem_map will * throw a UC_ERR_ARG error. */ u32 round_start = startat & (u32) (~0xFFF); u32 offset = startat - round_start; int errcode = 0; int roundlength = roundup(bytelength); uc_engine *uc; uc_err err; uc_hook hook1; int sys_abi_len; uc_mode mode; int ret_inst; int *sys_abi_vec; if (DEBUG){ printf("IN EMULATOR\n"); fdump(stdout, code, bytelength); } switch (arch) { case UC_ARCH_X86 : sys_abi_vec = x86_64_syscall_abi; // careful sys_abi_len = x86_64_syscall_abi_len; mode = UC_MODE_64; ret_inst = UC_X86_INS_RET; break; case UC_ARCH_ARM : if (DEBUG) printf("Emulating ARM architecture...\n"); sys_abi_vec = arm_32_syscall_abi; sys_abi_len = arm_32_syscall_abi_len; mode = UC_MODE_ARM; break; default : fprintf(stderr,"Unknown architecture requested of em_code.\nExiting.\n"); exit(EXIT_FAILURE); } union seedvals { word words[sys_abi_len]; u8 bytes[sys_abi_len * sizeof(word)]; } seedvals; /* fprintf(stderr, "bytelength = %d\nroundlength = %d\nsizeof(seedvals.bytes) = %d\nsizeof(seed_res) = %d\nsizeof(word) * sys_abi_len = %d\n",bytelength, roundlength, sizeof(seedvals.bytes), sizeof(seed_res), (sys_abi_len * sizeof(word))); */ if (!memcpy(seedvals.bytes, seed_res, (sys_abi_len * sizeof(word)))){ fprintf(stderr, "Error in memcpy, in em_code.\n"); } /** * from the unicorn src: "This part of the API is less... clean... * because Unicorn supports arbitrary register types. So the least * intrusive solution is passing individual pointers. On the plus * side, you only need to make this pointer array once." */ void *ptrs[sys_abi_len]; int i; for (i = 0; i < sys_abi_len; i++) { ptrs[i] = &(seedvals.words[i]); } if ((err = uc_open(arch, mode, &uc))) { uc_perror("uc_open", err); return -1; } // seed the registers if ((err = uc_reg_write_batch(uc, sys_abi_vec, ptrs, sys_abi_len))){ uc_perror("uc_reg_write_batch", err); return -1; } /* Add a single-stepping hook if debugging */ if (DEBUG){ if ((err = uc_hook_add(uc, &hook1, UC_HOOK_CODE, hook_step, NULL, 1, 0, 0))) { uc_perror("uc_hook_add", err); return 1; } } // don't leave 0x1000 a magic number if ((err = uc_mem_map(uc, round_start, 0x1000, UC_PROT_ALL))) { // does PROT_ALL mean 777? might want to set to XN for ROP... uc_perror("uc_mem_map", err); return -1; } if ((err = uc_mem_write(uc, startat, (void *) code, bytelength-1))) { uc_perror("uc_mem_write", err); return -1; } // why does the unicorn example suggest sizeof(CODE) -1 // where I have bytelength (sizeof(CODE))? probably because // it's implemented as a string, so it ends with a null byte if ((err = uc_emu_start(uc, startat, startat + bytelength -1, 0, TTL))){ if (DEBUG){ uc_perror("uc_emu_start", err); if (err == UC_ERR_FETCH_UNMAPPED) ret_msg(uc, err, arch); } errcode = -2; } uc_reg_read_batch(uc, sys_abi_vec, ptrs, sys_abi_len); /** for testing **/ if (DEBUG) { printf("syscall vec: {"); for (i = 0; i < sys_abi_len; i++) { if (i != 0) printf(", "); printf(WORDFMT, seedvals.words[i]); } printf("}\n"); } /******************/ memcpy(seed_res, seedvals.bytes, (sys_abi_len * sizeof(word))); return errcode; }