int main(int argc, char **argv) { FILE *acctf; const char *cp, *printer; printer = NULL; euid = geteuid(); /* these aren't used in pac(1) */ uid = getuid(); while (--argc) { cp = *++argv; if (*cp++ == '-') { switch(*cp++) { case 'P': /* * Printer name. */ printer = cp; continue; case 'p': /* * get the price. */ price = atof(cp); pflag = 1; continue; case 's': /* * Summarize and compress accounting file. */ summarize++; continue; case 'c': /* * Sort by cost. */ sort++; continue; case 'm': /* * disregard machine names for each user */ mflag = 1; continue; case 'r': /* * Reverse sorting order. */ reverse++; continue; default: usage(); } } (void) enter(--cp); allflag = 0; } if (printer == NULL && (printer = getenv("PRINTER")) == NULL) printer = DEFLP; if (!chkprinter(printer)) { printf("pac: unknown printer %s\n", printer); exit(2); } if ((acctf = fopen(acctfile, "r")) == NULL) { perror(acctfile); exit(1); } account(acctf); fclose(acctf); if ((acctf = fopen(sumfile, "r")) != NULL) { account(acctf); fclose(acctf); } if (summarize) rewrite(); else dumpit(); exit(errs); }
int main(int argc, char **argv) { FILE *acct; int ch; /* these aren't actually used in pac(1) */ effective_uid = geteuid(); real_uid = getuid(); effective_gid = getegid(); real_gid = getgid(); while ((ch = getopt(argc, argv, "P:p:scmr")) != -1) { switch (ch) { case 'P': /* * Printer name. */ printer = optarg; continue; case 'p': /* * get the price. */ price = atof(optarg); pflag = 1; continue; case 's': /* * Summarize and compress accounting file. */ summarize++; continue; case 'c': /* * Sort by cost. */ sort++; continue; case 'm': /* * disregard machine names for each user */ mflag = 1; continue; case 'r': /* * Reverse sorting order. */ reverse++; continue; default: usage(); /* NOTREACHED */ } } argc -= optind; argv += optind; /* * If there are any arguments left, they're names of users * we want to print info for. In that case, put them in the hash * table and unset allflag. */ for( ; argc > 0; argc--, argv++) { (void)enter(*argv); allflag = 0; } if (printer == NULL && (printer = getenv("PRINTER")) == NULL) printer = DEFLP; if (!chkprinter(printer)) errx(2, "unknown printer: %s", printer); if ((acct = fopen(acctfile, "r")) == NULL) err(1, "%s", acctfile); account(acct); fclose(acct); if ((acct = fopen(sumfile, "r")) != NULL) { account(acct); fclose(acct); } if (summarize) rewrite(); else dumpit(); exit(errs); }
static off_t _elf64_layout(Elf *elf, unsigned *flag) { int layout = (elf->e_elf_flags & ELF_F_LAYOUT) == 0; Elf64_Ehdr *ehdr = (Elf64_Ehdr*)elf->e_ehdr; size_t off = 0; unsigned version; unsigned encoding; size_t align_addr; size_t entsize; unsigned shnum; Elf_Scn *scn; *flag = elf->e_elf_flags | elf->e_phdr_flags; if ((version = ehdr->e_version) == EV_NONE) { version = EV_CURRENT; } if (!valid_version(version)) { seterr(ERROR_UNKNOWN_VERSION); return -1; } if ((encoding = ehdr->e_ident[EI_DATA]) == ELFDATANONE) { encoding = native_encoding; } if (!valid_encoding(encoding)) { seterr(ERROR_UNKNOWN_ENCODING); return -1; } entsize = _fsize(ELFCLASS64, version, ELF_T_EHDR); elf_assert(entsize); rewrite(ehdr->e_ehsize, entsize, elf->e_ehdr_flags); off = entsize; align_addr = _fsize(ELFCLASS64, version, ELF_T_ADDR); elf_assert(align_addr); if (elf->e_phnum) { entsize = _fsize(ELFCLASS64, version, ELF_T_PHDR); elf_assert(entsize); if (layout) { align(off, align_addr); rewrite(ehdr->e_phoff, off, elf->e_ehdr_flags); off += elf->e_phnum * entsize; } else { off = max(off, ehdr->e_phoff + elf->e_phnum * entsize); } } else { entsize = 0; if (layout) { rewrite(ehdr->e_phoff, 0, elf->e_ehdr_flags); } } rewrite(ehdr->e_phnum, elf->e_phnum, elf->e_ehdr_flags); rewrite(ehdr->e_phentsize, entsize, elf->e_ehdr_flags); for (scn = elf->e_scn_1, shnum = 0; scn; scn = scn->s_link, ++shnum) { Elf64_Shdr *shdr = &scn->s_shdr64; size_t scn_align = 1; off_t len; elf_assert(scn->s_index == shnum); *flag |= scn->s_scn_flags; if (scn->s_index == SHN_UNDEF) { rewrite(shdr->sh_entsize, 0, scn->s_shdr_flags); if (layout) { rewrite(shdr->sh_offset, 0, scn->s_shdr_flags); rewrite(shdr->sh_size, 0, scn->s_shdr_flags); rewrite(shdr->sh_addralign, 0, scn->s_shdr_flags); } *flag |= scn->s_shdr_flags; continue; } if (shdr->sh_type == SHT_NULL) { *flag |= scn->s_shdr_flags; continue; } len = scn_data_layout(scn, version, shdr->sh_type, &scn_align, flag); if (len == -1) { return -1; } /* * Never override the program's choice. */ if (shdr->sh_entsize == 0) { entsize = scn_entsize(elf, version, shdr->sh_type); if (entsize > 1) { rewrite(shdr->sh_entsize, entsize, scn->s_shdr_flags); } } if (layout) { align(off, scn_align); rewrite(shdr->sh_offset, off, scn->s_shdr_flags); rewrite(shdr->sh_size, (size_t)len, scn->s_shdr_flags); rewrite(shdr->sh_addralign, scn_align, scn->s_shdr_flags); if (shdr->sh_type != SHT_NOBITS) { off += (size_t)len; } } else if ((size_t)len > shdr->sh_size) { seterr(ERROR_SCN2SMALL); return -1; } else { Elf_Scn *scn2; size_t end1, end2; end1 = shdr->sh_offset; if (shdr->sh_type != SHT_NOBITS) { end1 += shdr->sh_size; } if (shdr->sh_offset < off) { /* * check for overlapping sections */ for (scn2 = elf->e_scn_1; scn2; scn2 = scn2->s_link) { if (scn2 == scn) { break; } end2 = scn2->s_shdr64.sh_offset; if (scn2->s_shdr64.sh_type != SHT_NOBITS) { end2 += scn2->s_shdr64.sh_size; } if (end1 > scn2->s_shdr64.sh_offset && end2 > shdr->sh_offset) { seterr(ERROR_SCN_OVERLAP); return -1; } } } if (off < end1) { off = end1; } } *flag |= scn->s_shdr_flags; } if (shnum) { entsize = _fsize(ELFCLASS64, version, ELF_T_SHDR); elf_assert(entsize); if (layout) { align(off, align_addr); rewrite(ehdr->e_shoff, off, elf->e_ehdr_flags); off += shnum * entsize; } else { off = max(off, ehdr->e_shoff + shnum * entsize); } } else { entsize = 0; if (layout) { rewrite(ehdr->e_shoff, 0, elf->e_ehdr_flags); } } if (shnum >= SHN_LORESERVE) { Elf_Scn *scn = elf->e_scn_1; Elf64_Shdr *shdr = &scn->s_shdr64; elf_assert(scn->s_index == 0); rewrite(shdr->sh_size, shnum, scn->s_shdr_flags); *flag |= scn->s_shdr_flags; shnum = 0; } rewrite(ehdr->e_shnum, shnum, elf->e_ehdr_flags); rewrite(ehdr->e_shentsize, entsize, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_MAG0], ELFMAG0, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_MAG1], ELFMAG1, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_MAG2], ELFMAG2, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_MAG3], ELFMAG3, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_CLASS], ELFCLASS64, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_DATA], encoding, elf->e_ehdr_flags); rewrite(ehdr->e_ident[EI_VERSION], version, elf->e_ehdr_flags); rewrite(ehdr->e_version, version, elf->e_ehdr_flags); *flag |= elf->e_ehdr_flags; return off; }
static off_t scn_data_layout(Elf_Scn *scn, unsigned v, unsigned type, size_t *algn, unsigned *flag) { Elf *elf = scn->s_elf; Elf_Data *data; int layout = (elf->e_elf_flags & ELF_F_LAYOUT) == 0; size_t scn_align = 1; size_t len = 0; Scn_Data *sd; size_t fsize; if (!(sd = scn->s_data_1)) { /* no data in section */ *algn = scn_align; return (off_t)len; } /* load data from file, if any */ if (!(data = elf_getdata(scn, NULL))) { return (off_t)-1; } elf_assert(data == &sd->sd_data); for (; sd; sd = sd->sd_link) { elf_assert(sd->sd_magic == DATA_MAGIC); elf_assert(sd->sd_scn == scn); if (!valid_version(sd->sd_data.d_version)) { return (off_t)-1; } fsize = sd->sd_data.d_size; if (fsize && type != SHT_NOBITS && valid_type(sd->sd_data.d_type)) { if (elf->e_class == ELFCLASS32) { fsize = _elf32_xltsize(&sd->sd_data, v, ELFDATA2LSB, 1); } #if __LIBELF64 else if (elf->e_class == ELFCLASS64) { fsize = _elf64_xltsize(&sd->sd_data, v, ELFDATA2LSB, 1); } #endif /* __LIBELF64 */ else { elf_assert(valid_class(elf->e_class)); seterr(ERROR_UNIMPLEMENTED); return (off_t)-1; } if (fsize == (size_t)-1) { return (off_t)-1; } } if (layout) { align(len, sd->sd_data.d_align); scn_align = max(scn_align, sd->sd_data.d_align); rewrite(sd->sd_data.d_off, (off_t)len, sd->sd_data_flags); len += fsize; } else { len = max(len, sd->sd_data.d_off + fsize); } *flag |= sd->sd_data_flags; } *algn = scn_align; return (off_t)len; }
bool Dictionary::compile(const Param ¶m, const std::vector<std::string> &dics, const char *matrix_file, const char *matrix_bin_file, const char *left_id_file, const char *right_id_file, const char *rewrite_file, const char *pos_id_file, const char *output) { Connector matrix; scoped_ptr<DictionaryRewriter> rewrite(0); scoped_ptr<POSIDGenerator> posid(0); scoped_ptr<ContextID> cid(0); scoped_ptr<Writer> writer(0); scoped_ptr<StringBuffer> os(0); Node node; std::vector<std::pair<std::string, Token*> > dic; size_t offset = 0; unsigned int lexsize = 0; std::string w, feature, ufeature, lfeature, rfeature, fbuf, key; int lid, rid, cost; const std::string from = param.get<std::string>("dictionary-charset"); const std::string to = param.get<std::string>("charset"); const bool wakati = param.get<bool>("wakati"); const int type = param.get<int>("type"); const std::string node_format = param.get<std::string>("node-format"); // for backward compatibility std::string config_charset = param.get<std::string>("config-charset"); if (config_charset.empty()) config_charset = from; CHECK_DIE(!from.empty()) << "input dictionary charset is empty"; CHECK_DIE(!to.empty()) << "output dictionary charset is empty"; Iconv iconv; CHECK_DIE(iconv.open(from.c_str(), to.c_str())) << "iconv_open() failed with from=" << from << " to=" << to; Iconv config_iconv; CHECK_DIE(config_iconv.open(config_charset.c_str(), from.c_str())) << "iconv_open() failed with from=" << config_charset << " to=" << from; if (!node_format.empty()) { writer.reset(new Writer); os.reset(new StringBuffer); memset(&node, 0, sizeof(node)); } if (!matrix.openText(matrix_file) && !matrix.open(matrix_bin_file)) { matrix.set_left_size(1); matrix.set_right_size(1); } posid.reset(new POSIDGenerator); posid->open(pos_id_file, &config_iconv); std::istringstream iss(UNK_DEF_DEFAULT); for (size_t i = 0; i < dics.size(); ++i) { std::ifstream ifs(dics[i].c_str()); std::istream *is = &ifs; if (!ifs) { if (type == MECAB_UNK_DIC) { std::cerr << dics[i] << " is not found. minimum setting is used." << std::endl; is = &iss; } else { CHECK_DIE(ifs) << "no such file or directory: " << dics[i]; } } std::cout << "reading " << dics[i] << " ... "; char line[BUF_SIZE]; size_t num = 0; while (is->getline(line, sizeof(line))) { char *col[8]; const size_t n = tokenizeCSV(line, col, 5); CHECK_DIE(n == 5) << "format error: " << line; w = col[0]; lid = std::atoi(col[1]); rid = std::atoi(col[2]); cost = std::atoi(col[3]); feature = col[4]; int pid = posid->id(feature.c_str()); if (lid < 0 || rid < 0) { if (!rewrite.get()) { rewrite.reset(new DictionaryRewriter); rewrite->open(rewrite_file, &config_iconv); } CHECK_DIE(rewrite->rewrite(feature, &ufeature, &lfeature, &rfeature)) << "rewrite failed: " << feature; if (!cid.get()) { cid.reset(new ContextID); cid->open(left_id_file, right_id_file, &config_iconv); CHECK_DIE(cid->left_size() == matrix.left_size() && cid->right_size() == matrix.right_size()) << "Context ID files(" << left_id_file << " or " << right_id_file << " may be broken"; } lid = cid->lid(lfeature.c_str()); rid = cid->rid(rfeature.c_str()); } CHECK_DIE(lid >= 0 && rid >= 0 && matrix.is_valid(lid, rid)) << "invalid ids are found lid=" << lid << " rid=" << rid; if (w.empty()) { std::cerr << "empty word is found, discard this line" << std::endl; continue; } if (!iconv.convert(&feature)) { std::cerr << "iconv conversion failed. skip this entry" << std::endl; continue; } if (type != MECAB_UNK_DIC && !iconv.convert(&w)) { std::cerr << "iconv conversion failed. skip this entry" << std::endl; continue; } if (!node_format.empty()) { node.surface = w.c_str(); node.feature = feature.c_str(); node.length = w.size(); node.rlength = w.size(); node.posid = pid; node.stat = MECAB_NOR_NODE; CHECK_DIE(os.get()); CHECK_DIE(writer.get()); os->clear(); CHECK_DIE(writer->writeNode(&*os, node_format.c_str(), w.c_str(), &node)) << "conversion error: " << feature << " with " << node_format; *os << '\0'; feature = os->str(); } key.clear(); if (!wakati) key = feature + '\0'; Token* token = new Token; token->lcAttr = lid; token->rcAttr = rid; token->posid = pid; token->wcost = cost; token->feature = offset; token->compound = 0; dic.push_back(std::make_pair<std::string, Token*>(w, token)); // append to output buffer if (!wakati) fbuf.append(key.data(), key.size()); offset += key.size(); ++num; ++lexsize; } std::cout << num << std::endl; } if (wakati) fbuf.append("\0", 1); std::sort(dic.begin(), dic.end()); size_t bsize = 0; size_t idx = 0; std::string prev; std::vector<const char *> str; std::vector<size_t> len; std::vector<Darts::DoubleArray::result_type> val; for (size_t i = 0; i < dic.size(); ++i) { if (i != 0 && prev != dic[i].first) { str.push_back(dic[idx].first.c_str()); len.push_back(dic[idx].first.size()); val.push_back(bsize +(idx << 8)); bsize = 1; idx = i; } else { ++bsize; } prev = dic[i].first; } str.push_back(dic[idx].first.c_str()); len.push_back(dic[idx].first.size()); val.push_back(bsize +(idx << 8)); CHECK_DIE(str.size() == len.size()); CHECK_DIE(str.size() == val.size()); Darts::DoubleArray da; CHECK_DIE(da.build(str.size(), const_cast<char **>(&str[0]), &len[0], &val[0], &progress_bar_darts) == 0) << "unkown error in building double-array"; std::string tbuf; for (size_t i = 0; i < dic.size(); ++i) { tbuf.append(reinterpret_cast<const char*>(dic[i].second), sizeof(Token)); delete dic[i].second; } dic.clear(); // needs to be 8byte(64bit) aligned while (tbuf.size() % 8 != 0) { Token dummy; memset(&dummy, 0, sizeof(Token)); tbuf.append(reinterpret_cast<const char*>(&dummy), sizeof(Token)); } unsigned int dummy = 0; unsigned int lsize = matrix.left_size(); unsigned int rsize = matrix.right_size(); unsigned int dsize = da.unit_size() * da.size(); unsigned int tsize = tbuf.size(); unsigned int fsize = fbuf.size(); unsigned int version = DIC_VERSION; char charset[32]; std::fill(charset, charset + sizeof(charset), '\0'); std::strncpy(charset, to.c_str(), 31); std::ofstream bofs(output, std::ios::binary|std::ios::out); CHECK_DIE(bofs) << "permission denied: " << output; unsigned int magic = 0; // needs to be 64bit aligned // 10*32 = 64*5 bofs.write(reinterpret_cast<const char *>(&magic), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&version), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&type), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&lexsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&lsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&rsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&dsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&tsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&fsize), sizeof(unsigned int)); bofs.write(reinterpret_cast<const char *>(&dummy), sizeof(unsigned int)); // 32 * 8 = 64 * 4 bofs.write(reinterpret_cast<const char *>(charset), sizeof(charset)); bofs.write(reinterpret_cast<const char*>(da.array()), da.unit_size() * da.size()); bofs.write(const_cast<const char *>(tbuf.data()), tbuf.size()); bofs.write(const_cast<const char *>(fbuf.data()), fbuf.size()); // save magic id magic = static_cast<unsigned int>(bofs.tellp()); magic ^= DictionaryMagicID; bofs.seekp(0); bofs.write(reinterpret_cast<const char *>(&magic), sizeof(unsigned int)); bofs.close(); return true; }
static Node * bin_simpler(Node *ptr) { Node *a, *b; if (ptr) switch (ptr->ntyp) { case U_OPER: #ifndef NO_OPT if (ptr->rgt->ntyp == TRUE || ptr->rgt->ntyp == FALSE || ptr->lft->ntyp == FALSE) { ptr = ptr->rgt; break; } if (isequal(ptr->lft, ptr->rgt)) { /* p U p = p */ ptr = ptr->rgt; break; } if (ptr->lft->ntyp == U_OPER && isequal(ptr->lft->lft, ptr->rgt)) { /* (p U q) U p = (q U p) */ ptr->lft = ptr->lft->rgt; break; } if (ptr->rgt->ntyp == U_OPER && ptr->rgt->lft->ntyp == TRUE) { /* p U (T U q) = (T U q) */ ptr = ptr->rgt; break; } #ifdef NXT /* X p U X q == X (p U q) */ if (ptr->rgt->ntyp == NEXT && ptr->lft->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(U_OPER, ptr->lft->lft, ptr->rgt->lft), ZN); } #endif #endif break; case V_OPER: #ifndef NO_OPT if (ptr->rgt->ntyp == FALSE || ptr->rgt->ntyp == TRUE || ptr->lft->ntyp == TRUE) { ptr = ptr->rgt; break; } if (isequal(ptr->lft, ptr->rgt)) { /* p V p = p */ ptr = ptr->rgt; break; } /* F V (p V q) == F V q */ if (ptr->lft->ntyp == FALSE && ptr->rgt->ntyp == V_OPER) { ptr->rgt = ptr->rgt->rgt; break; } /* p V (F V q) == F V q */ if (ptr->rgt->ntyp == V_OPER && ptr->rgt->lft->ntyp == FALSE) { ptr->lft = False; ptr->rgt = ptr->rgt->rgt; break; } #endif break; case IMPLIES: #ifndef NO_OPT if (isequal(ptr->lft, ptr->rgt)) { ptr = True; break; } #endif ptr = tl_nn(OR, Not(ptr->lft), ptr->rgt); ptr = rewrite(ptr); break; case EQUIV: #ifndef NO_OPT if (isequal(ptr->lft, ptr->rgt)) { ptr = True; break; } #endif a = rewrite(tl_nn(AND, dupnode(ptr->lft), dupnode(ptr->rgt))); b = rewrite(tl_nn(AND, Not(ptr->lft), Not(ptr->rgt))); ptr = tl_nn(OR, a, b); ptr = rewrite(ptr); break; case AND: #ifndef NO_OPT /* p && (q U p) = p */ if (ptr->rgt->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->lft; break; } if (ptr->lft->ntyp == U_OPER && isequal(ptr->lft->rgt, ptr->rgt)) { ptr = ptr->rgt; break; } /* p && (q V p) == q V p */ if (ptr->rgt->ntyp == V_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->rgt; break; } if (ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt)) { ptr = ptr->lft; break; } /* (p U q) && (r U q) = (p && r) U q*/ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft->rgt)) { ptr = tl_nn(U_OPER, tl_nn(AND, ptr->lft->lft, ptr->rgt->lft), ptr->lft->rgt); break; } /* (p V q) && (p V r) = p V (q && r) */ if (ptr->rgt->ntyp == V_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->rgt->lft, ptr->lft->lft)) { ptr = tl_nn(V_OPER, ptr->rgt->lft, tl_nn(AND, ptr->lft->rgt, ptr->rgt->rgt)); break; } #ifdef NXT /* X p && X q == X (p && q) */ if (ptr->rgt->ntyp == NEXT && ptr->lft->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(AND, ptr->rgt->lft, ptr->lft->lft), ZN); break; } #endif if (isequal(ptr->lft, ptr->rgt) /* (p && p) == p */ || ptr->rgt->ntyp == FALSE /* (p && F) == F */ || ptr->lft->ntyp == TRUE) /* (T && p) == p */ { ptr = ptr->rgt; break; } if (ptr->rgt->ntyp == TRUE /* (p && T) == p */ || ptr->lft->ntyp == FALSE) /* (F && p) == F */ { ptr = ptr->lft; break; } /* (p V q) && (r U q) == p V q */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = ptr->lft; break; } #endif break; case OR: #ifndef NO_OPT /* p || (q U p) == q U p */ if (ptr->rgt->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->rgt; break; } /* p || (q V p) == p */ if (ptr->rgt->ntyp == V_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->lft; break; } /* (p U q) || (p U r) = p U (q || r) */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == U_OPER && isequal(ptr->rgt->lft, ptr->lft->lft)) { ptr = tl_nn(U_OPER, ptr->rgt->lft, tl_nn(OR, ptr->lft->rgt, ptr->rgt->rgt)); break; } if (isequal(ptr->lft, ptr->rgt) /* (p || p) == p */ || ptr->rgt->ntyp == FALSE /* (p || F) == p */ || ptr->lft->ntyp == TRUE) /* (T || p) == T */ { ptr = ptr->lft; break; } if (ptr->rgt->ntyp == TRUE /* (p || T) == T */ || ptr->lft->ntyp == FALSE) /* (F || p) == p */ { ptr = ptr->rgt; break; } /* (p V q) || (r V q) = (p || r) V q */ if (ptr->rgt->ntyp == V_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = tl_nn(V_OPER, tl_nn(OR, ptr->lft->lft, ptr->rgt->lft), ptr->rgt->rgt); break; } /* (p V q) || (r U q) == r U q */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = ptr->rgt; break; } #endif break; } return ptr; }
int dump_cond(Node *pp, Node *r, int first) { Node *q; int frst = first; if (!pp) return frst; q = dupnode(pp); q = rewrite(q); if (q->ntyp == CEXPR) { if (!frst) fprintf(tl_out, " && "); fprintf(tl_out, "c_expr { "); dump_cond(q->lft, r, 1); fprintf(tl_out, " } "); frst = 0; return frst; } if (q->ntyp == PREDICATE || q->ntyp == NOT #ifndef NXT || q->ntyp == OR #endif || q->ntyp == FALSE) { if (!frst) fprintf(tl_out, " && "); dump(q); frst = 0; #ifdef NXT } else if (q->ntyp == OR) { if (!frst) fprintf(tl_out, " && "); fprintf(tl_out, "(("); frst = dump_cond(q->lft, r, 1); if (!frst) fprintf(tl_out, ") || ("); else { if (only_nxt(q->lft)) { fprintf(tl_out, "1))"); return 0; } } frst = dump_cond(q->rgt, r, 1); if (frst) { if (only_nxt(q->rgt)) fprintf(tl_out, "1"); else fprintf(tl_out, "0"); frst = 0; } fprintf(tl_out, "))"); #endif } else if (q->ntyp == V_OPER && !anywhere(AND, q->rgt, r)) { frst = dump_cond(q->rgt, r, frst); } else if (q->ntyp == AND) { frst = dump_cond(q->lft, r, frst); frst = dump_cond(q->rgt, r, frst); } return frst; }
/** * This is the main function of the program that handles calling other * functions to implemented the needed operations of the replay functionaily. */ int main(int argc, char **argv) { unsigned int k; int num_packets = 0; char port_mode[10]; /* does user specify random port generation?*/ char random_strg[7] = "random"; char* iface = argv[1]; char* new_rmac_ptr; char* new_rip_ptr; input_addr new_remoteip; struct mac_addr new_remotemac; input_addr myip; struct mac_addr mymac; unsigned int new_src_port = 0; unsigned int retransmissions = 0; pcap_t *local_handle; char errbuf[PCAP_ERRBUF_SIZE]; char ebuf[SENDPACKET_ERRBUF_SIZE]; optionProcess(&tcpliveplayOptions, argc, argv); /*Process AutoOpts for manpage options*/ if((argc < 5) || (argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL) || (argv[4]==NULL) || (argv[5]==NULL)){ printf("ERROR: Incorrect Usage!\n"); printf("Usage: tcpliveplay <eth0/eth1> <file.pcap> <Destinatin IP [1.2.3.4]> <Destination mac [0a:1b:2c:3d:4e:5f]> <specify 'random' or specific port#>\n"); printf("Example:\n yhsiam@yhsiam-VirtualBox:~$ sudo tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random\n\n"); exit(0); } if (iface_addrs(iface, &myip, &mymac) < 0) /* Extract MAC of interface replay is being request on */ errx(-1, "Failed to access interface %s\n", iface); /* open send function socket*/ if ((sp = sendpacket_open(iface, ebuf, TCPR_DIR_C2S, SP_TYPE_NONE, NULL)) == NULL) errx(-1, "Can't open %s: %s", argv[1], ebuf); /* random dport vs. specified dport operation*/ strcpy(port_mode, argv[5]); /*for(int i = 0; i<10; i++) tolower(port_mode[i]);*/ if(strcmp(port_mode, random_strg)==0){ new_src_port = random_port(); } else new_src_port = atoi(argv[5]); /*else { printf("Port specification error. Please specify 'random' for random source port generation between 49152 and 65535 OR specify a specific source port number.\n"); return; }*/ printf("new source port:: %d\n", new_src_port); /* Establish a handler for SIGALRM signals. */ /* This is used as timeout for unresponsive remote hosts */ signal (SIGALRM, catch_alarm); /* Extract new Remote MAC & IP inputed at command line */ new_rmac_ptr= argv[4]; new_rip_ptr = argv[3]; /* These function setup the MAC & IP addresses in the mac_addr & in_addr structs */ if (extmac(new_rmac_ptr, &new_remotemac) == ERROR) errx(-1, "failed to parse mac address %s\n", new_rmac_ptr); if (extip(new_rip_ptr, &new_remoteip) == ERROR) errx(-1, "failed to parse IP address %s\n", new_rip_ptr); /* Rewrites the given "*.pcap" file with all the new parameters and returns the number of packets */ /* that need to be replayed */ num_packets = rewrite(&new_remoteip, &new_remotemac, &myip, &mymac, argv[2], new_src_port); if (num_packets < 0) errx(-1, "Unable to rewrite PCAP file %s\n",argv[2]); /* create schedule & set it up */ sched = (struct tcp_sched*) malloc(num_packets*sizeof(struct tcp_sched)); if (!sched) err(-1, "out of memory\n"); pkts_scheduled = setup_sched(sched); /* Returns number of packets in schedule*/ /* Set up the schedule struct to be relative numbers rather than absolute*/ relative_sched(sched, sched[1].exp_rseq, num_packets); printf("Packets Scheduled %d\n", pkts_scheduled); /* Open socket for savedfile traffic to be sent*/ local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/ if (local_handle == NULL) { fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf); free(sched); return(2); } /* Open socket for live traffic to be listed to*/ live_handle = set_live_filter(iface, &myip, new_src_port); /* returns a pcap_t that filters out traffic other than TCP*/ if (live_handle == NULL) { fprintf(stderr,"Error occured while listing on traffic: %s\n", errbuf); free(sched); return(2); } /* Printout when no packets are scheduled */ if(pkts_scheduled==0){ printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ ERROR:: There are no TCP packets to send +\n"); printf("+ Closing replay... +\n"); printf("+ Thank you for Playing, Play again! +\n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); free(sched); return ERROR; } /* Start replay by sending the first packet, the SYN, from the schedule */ else if(sched[0].local){ /* Send first packet*/ sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr); printf("Sending Local Packet............... [%d]\n",sched_index+1); sched_index++; /* Proceed in the schedule */ } /* Main while loop that handles the decision making and the replay oprations */ while(sched_index<pkts_scheduled){ if(!keep_going) { /*Check the timeout variable */ printf("\n======================================================================\n"); printf("= TIMEOUT:: Remote host is not responding. You may have crashed =\n"); printf("= the host you replayed these packets against OR the packet sequence =\n"); printf("= changed since the capture was taken resulting in differing =\n"); printf("= expectations. Closing replay... =\n"); printf("======================================================================\n\n"); break; } /* tcphdr_rprev carries the last remote tcp header */ if(tcphdr_rprev == NULL) { //printf("FIRST PASS!\n"); } /* Check if received RST or RST-ACK flagged packets*/ else if((tcphdr_rprev->th_flags==TH_RST) || (tcphdr_rprev->th_flags==(TH_RST|TH_ACK))){ printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ ERROR:: Remote host has requested to RESET the connection. +\n"); printf("+ Closing replay... +\n"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); break; } /*Check if received earlier FIN-ACK than expected else if((sched_index-1 < finack_rindex) && (tcphdr_rprev->th_flags==(TH_FIN|TH_ACK))){ printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ ERROR:: Remote host sent an earlier FIN-ACK than expected. +\n"); printf("+ Closing replay... +\n"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); return; } */ /* Do the following if we receive a packet that ACKs for the same ACKing of next packet */ else if((tcphdr_rprev->th_seq==htonl(sched[sched_index].exp_rseq)) && (tcphdr_rprev->th_ack==htonl(sched[sched_index].exp_rack)) && (size_payload_prev>0)){ printf("Received Remote Packet............... [%d]\n",sched_index+1); printf("Skipping Packet...................... [%d] to Packet [%d]\n",sched_index+1, sched_index+2); printf("Next Remote Packet Expectation met.\nProceeding in replay...\n"); sched_index++; } /* Do the following if payload does not meet expectation and re-attempt with the remote host for 3 tries*/ else if(different_payload){ printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ WARNING: Remote host is not meeting packet size expectations. +\n"); printf("+ for packet %-d. Application layer data differs from capture being replayed. +\n", diff_payload_index+1); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); printf("Requesting retransmission.\n Proceeding...\n"); different_payload = false; } /* Local Packets */ if(sched[sched_index].local) { /*Reset alarm timeout*/ alarm (ALARM_TIMEOUT); printf("Sending Local Packet............... [%d]\n",sched_index+1); /* edit each packet tcphdr before sending based on the schedule*/ if(sched_index>0){ sched[sched_index].tcphdr->th_ack = htonl(sched[sched_index].curr_lack); fix_all_checksum_liveplay(sched[sched_index].iphdr); } /* If 3 attempts of resending was made, then error out to the user */ if(sched[sched_index].sent_counter==3){ printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); printf("+ ERROR: Re-sent packet [%-d] 3 times, but remote host is not +\n", sched_index+1); printf("+ responding as expected. 3 resend attempts are a maximum. +\n"); printf("+ Closing replay... +\n"); printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); break; } /* If nothing goes wrong, then send the packet scheduled to be sent, then proceed in the schedule */ sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr); sched[sched_index].sent_counter++; /* Keep track of how many times this specific packet was attempted */ sched_index++; /* proceed */ } /* Remote Packets */ else if(sched[sched_index].remote){ alarm (ALARM_TIMEOUT); printf("Receiving Packets from remote host...\n"); pcap_dispatch(live_handle, 1, got_packet, NULL); /* Listen in on NIC for tcp packets */ //printf("pcap_loop returned\n"); } } /* end of main while loop*/ pcap_breakloop(live_handle); pcap_close(live_handle); sendpacket_close(sp); /* Close Send socket*/ remove("newfile.pcap"); /* Remote the rewritten file that was created*/ for(k=0; k<pkts_scheduled; k++){ retransmissions+=sched[k].sent_counter; } /* User Debug Result Printouts*/ if(sched_index==pkts_scheduled){ printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("~ CONGRATS!!! You have successfully Replayed your pcap file '%s' \n", argv[2]); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); } else { printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); printf("~ Unfortunately an error has occurred halting the replay of \n"); printf("~ the pcap file '%s'. Please see error above for details... \n", argv[2]); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); } printf("----------------TCP Live Play Summary----------------\n"); printf("- Packets Scheduled to be Sent & Received: %-d \n", pkts_scheduled); printf("- Actual Packets Sent & Received: %-d \n", sched_index); printf("- Total Local Packet Re-Transmissions due to packet \n"); printf("- loss and/or differing payload size than expected: %-d \n", retransmissions); printf("- Thank you for Playing, Play again! \n"); printf("----------------------------------------------------------\n\n"); free(sched); return 0; }
int main(int argv, char** argc) { if (argv == 1) { std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n"; return 0; } if (argv == 2 && (std::string(argc[1]) == "--help" || std::string(argc[1]) == "-h" )) { std::cout << argc[1] << "\n"; std::cout << "serpent command input\n"; std::cout << "where input -s for from stdin, a file, or interpreted as serpent code if does not exist as file."; std::cout << "where command: \n"; std::cout << " parse: Just parses and returns s-expression code.\n"; std::cout << " rewrite: Parse, use rewrite rules print s-expressions of result.\n"; std::cout << " compile: Return resulting compiled EVM code in hex.\n"; std::cout << " assemble: Return result from step before compilation.\n"; return 0; } std::string flag = ""; std::string command = argc[1]; std::string input; std::string secondInput; if (std::string(argc[1]) == "-s") { flag = command.substr(1); command = argc[2]; input = ""; std::string line; while (std::getline(std::cin, line)) { input += line + "\n"; } secondInput = argv == 3 ? "" : argc[3]; } else { if (argv == 2) { std::cerr << "Not enough arguments for serpent cmdline\n"; throw(0); } input = argc[2]; secondInput = argv == 3 ? "" : argc[3]; } bool haveSec = secondInput.length() > 0; if (command == "parse" || command == "parse_serpent") { std::cout << printAST(parseSerpent(input), haveSec) << "\n"; } else if (command == "rewrite") { std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_to_lll") { std::cout << printAST(compileToLLL(input), haveSec) << "\n"; } else if (command == "rewrite_chunk") { std::cout << printAST(rewriteChunk(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_chunk_to_lll") { std::cout << printAST(compileChunkToLLL(input), haveSec) << "\n"; } else if (command == "build_fragtree") { std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n"; } else if (command == "compile_lll") { std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n"; } else if (command == "dereference") { std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n"; } else if (command == "pretty_assemble") { std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n"; } else if (command == "pretty_compile_lll") { std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n"; } else if (command == "pretty_compile") { std::cout << printTokens(prettyCompile(input)) << "\n"; } else if (command == "pretty_compile_chunk") { std::cout << printTokens(prettyCompileChunk(input)) << "\n"; } else if (command == "assemble") { std::cout << assemble(parseLLL(input, true)) << "\n"; } else if (command == "serialize") { std::cout << binToHex(serialize(tokenize(input, Metadata(), false))) << "\n"; } else if (command == "flatten") { std::cout << printTokens(flatten(parseLLL(input, true))) << "\n"; } else if (command == "deserialize") { std::cout << printTokens(deserialize(hexToBin(input))) << "\n"; } else if (command == "compile") { std::cout << binToHex(compile(input)) << "\n"; } else if (command == "compile_chunk") { std::cout << binToHex(compileChunk(input)) << "\n"; } else if (command == "encode_datalist") { std::vector<Node> tokens = tokenize(input); std::vector<std::string> o; for (int i = 0; i < (int)tokens.size(); i++) { o.push_back(tokens[i].val); } std::cout << binToHex(encodeDatalist(o)) << "\n"; } else if (command == "decode_datalist") { std::vector<std::string> o = decodeDatalist(hexToBin(input)); std::vector<Node> tokens; for (int i = 0; i < (int)o.size(); i++) tokens.push_back(token(o[i])); std::cout << printTokens(tokens) << "\n"; } else if (command == "tokenize") { std::cout << printTokens(tokenize(input)); } else if (command == "biject") { if (argv == 3) std::cerr << "Not enough arguments for biject\n"; int pos = decimalToUnsigned(secondInput); std::vector<Node> n = prettyCompile(input); if (pos >= (int)n.size()) std::cerr << "Code position too high\n"; Metadata m = n[pos].metadata; std::cout << "Opcode: " << n[pos].val << ", file: " << m.file << ", line: " << m.ln << ", char: " << m.ch << "\n"; } }
Node * push_negation(Node *n) { Node *m; Assert(n->ntyp == NOT, n->ntyp); switch (n->lft->ntyp) { case TRUE: Debug("!true => false\n"); releasenode(0, n->lft); n->lft = ZN; n->ntyp = FALSE; break; case FALSE: Debug("!false => true\n"); releasenode(0, n->lft); n->lft = ZN; n->ntyp = TRUE; break; case NOT: Debug("!!p => p\n"); m = n->lft->lft; releasenode(0, n->lft); n->lft = ZN; releasenode(0, n); n = m; break; case V_OPER: Debug("!(p V q) => (!p U !q)\n"); n->ntyp = U_OPER; goto same; case U_OPER: Debug("!(p U q) => (!p V !q)\n"); n->ntyp = V_OPER; goto same; #ifdef NXT case NEXT: Debug("!X -> X!\n"); n->ntyp = NEXT; n->lft->ntyp = NOT; n->lft = push_negation(n->lft); break; #endif case AND: Debug("!(p && q) => !p || !q\n"); n->ntyp = OR; goto same; case OR: Debug("!(p || q) => !p && !q\n"); n->ntyp = AND; same: m = n->lft->rgt; n->lft->rgt = ZN; n->rgt = Not(m); n->lft->ntyp = NOT; m = n->lft; n->lft = push_negation(m); break; } return rewrite(n); }
int execvp(const char * path, char * const argv[]) { int (*_execvp) (const char *, char * const argv[]) = dlsym(RTLD_NEXT, "execvp"); char buf[PATH_MAX]; return _execvp(rewrite(path, buf), argv); }
virtual void visit(const RenamedPathExpression *pe) { auto pathExpr = rewrite(pe->getPathExpression()); expr = pathExpr(pe->getPathEndpoint(0), pe->getPathEndpoint(1)); }
virtual void visit(const Or *pe) { expr = Or::make(pe->getFreeVars(), pe->getQuantifiedVars(), rewrite(pe->getRhs()), rewrite(pe->getLhs())); }
/** * このシードを使って、道路生成する。 * Exampleベースで生成する。 */ bool PatchRoadGenerator::attemptExpansion(int roadType, RoadVertexDesc srcDesc, int ex_id, ExFeature& f, std::vector<Patch> &patches, std::list<RoadVertexDesc> &seeds) { RoadVertexDesc ex_v_desc; bool exampleFound = false; if (roadType == RoadEdge::TYPE_AVENUE) { if (roads.graph[srcDesc]->properties.contains("example_desc")) { if (roads.graph[srcDesc]->properties["ex_id"].toInt() == ex_id) { exampleFound = true; ex_v_desc = roads.graph[srcDesc]->properties["example_desc"].toUInt(); } } } else { if (roads.graph[srcDesc]->properties.contains("example_street_desc")) { if (roads.graph[srcDesc]->properties["ex_id"].toInt() == ex_id) { exampleFound = true; ex_v_desc = roads.graph[srcDesc]->properties["example_street_desc"].toUInt(); } } } float angle = roads.graph[srcDesc]->rotationAngle; //RoadVertexPtr ex_vertex = f.roads(roadType).graph[ex_v_desc]; int patch_id; RoadGraph replacementGraph; // パッチで生成された頂点でも、元のExampleで境界上の頂点である場合、次に対応するパッチがない。 // そこで、「パッチなし」とマークする。 if (exampleFound) { if (f.roads(roadType).graph[ex_v_desc]->onBoundary) { exampleFound = false; } } // 次の対応パッチが決まっていない場合、 if (!exampleFound) { Polyline2D polyline = GraphUtil::getAdjoiningPolyline(roads, srcDesc); float min_cost = std::numeric_limits<float>::max(); RoadVertexDesc root_desc; RoadVertexDesc connect_desc; std::reverse(polyline.begin(), polyline.end()); for (int i = 0; i < patches.size(); ++i) { // 現在の頂点が属するパッチと、同じパッチは、使わない。 // もし使っちゃったら、同じパッチが並んでしまう。 if (i == roads.graph[srcDesc]->patchId) continue; RoadVertexDesc v_connector; RoadVertexDesc v_root; float cost = patches[i].getMinCost(polyline, v_connector, v_root); if (cost < min_cost) { min_cost = cost; patch_id = i; connect_desc = v_connector; root_desc = v_root; } } // streetの場合は、example_street_descにしないといけないか? // いや、大丈夫。streetのパッチは、元のgraphの頂点IDを、やはりexample_descに格納しているから。 ex_v_desc = patches[patch_id].roads.graph[root_desc]->properties["example_desc"].toUInt(); buildReplacementGraphByExample2(roadType, replacementGraph, srcDesc, ex_id, f.roads(roadType), ex_v_desc, angle, patches[patch_id], patch_id, connect_desc, root_desc); } else { patch_id = f.roads(roadType).graph[ex_v_desc]->patchId; if (patch_id < 0) { printf("ERROR!!!!!!!!!!!!!!"); } buildReplacementGraphByExample(roadType, replacementGraph, srcDesc, ex_id, f.roads(roadType), ex_v_desc, angle, patches[patch_id], patch_id); } // replacementGraphが、既に生成済みのグラフと重なるかどうかチェック if (GraphUtil::isIntersect(replacementGraph, roads)) { int xxx = 0; return false; } rewrite(roadType, srcDesc, replacementGraph, seeds); return true; }
tree evaluate_rewrite (tree t) { return evaluate (rewrite (t)); }
// Rewrite relative path to absolute. static char *rewrite(const char *path, const int flag) { char *linkdir, *out; struct stat *buf; char temp[PATH_MAX+1], safe[PATH_MAX+1]; temp[0]='\0'; temp[PATH_MAX]='\0'; // Terminate string for safety :) safe[0]='\0'; safe[PATH_MAX]='\0'; // Terminate string for safety :) // To make sure path is not empty and defined. Return empty string if (!path || *path=='\0') return strndup(safe, 0); // Check if file exists buf=malloc(sizeof(struct stat)); if (lstat(path, buf)==0) { int type=(buf->st_mode & 0170000); int mode=(buf->st_mode & 07777); if (soapboxdebug & 8) { switch(type) { case S_IFLNK: sb_log(8, "File \"%s\" is a symlink. (%04o)", path, mode); break;; case S_IFREG: sb_log(8, "File \"%s\" is a regular file. (%04o)", path, mode); break;; case S_IFDIR: sb_log(8, "File \"%s\" is a directory. (%04o)", path, mode); break;; case S_IFCHR: sb_log(8, "File \"%s\" is a character device. (%04o)", path, mode); break;; case S_IFBLK: sb_log(8, "File \"%s\" is a block device. (%04o)", path, mode); break;; default: sb_log(8, "File \"%s\" is an unknown file type. (%04o)", path, mode); break;; } } // If it is a symlink and if asked (R_LINK), we should make its dirname absolute // (not the symlink) and add its basename if ((type==S_IFLNK) && (flag==R_LINK)) { linkdir=rewrite(dirname(path), R_LINK); snprintf(safe, PATH_MAX, "%s/%s", linkdir, basename(path)); free(linkdir); } else { realpath(path, safe); } } else { sb_log(8, "File \"%s\" does not exist.", path); realpath(path, safe); // TODO: Problem with non-existing files !! /* realpath(path, temp); // If the file doesn't exist, realpath() doesn't return its basename, so we need to add it ourselves // (TODO: If more than one subdirectory does not exist, this is WRONG. Alternative to realpath ?) if (strcmp(path, temp)) snprintf(safe, PATH_MAX, "%s/%s", temp, basename(path)); else snprintf(safe, PATH_MAX, "%s", temp); */ } free(buf); out=strndup(safe, strlen(safe)); if (strcmp(path, out)) sb_log(4, "File \"%s\" is actually \"%s\".", path, out); return out; }
static Node * bin_simpler(Node *ptr) { Node *a, *b; if (ptr) switch (ptr->ntyp) { case U_OPER: if (ptr->rgt->ntyp == TRUE || ptr->rgt->ntyp == FALSE || ptr->lft->ntyp == FALSE) { ptr = ptr->rgt; break; } if (implies(ptr->lft, ptr->rgt)) /* NEW */ { ptr = ptr->rgt; break; } if (ptr->lft->ntyp == U_OPER && isequal(ptr->lft->lft, ptr->rgt)) { /* (p U q) U p = (q U p) */ ptr->lft = ptr->lft->rgt; break; } if (ptr->rgt->ntyp == U_OPER && implies(ptr->lft, ptr->rgt->lft)) { /* NEW */ ptr = ptr->rgt; break; } #ifdef NXT /* X p U X q == X (p U q) */ if (ptr->rgt->ntyp == NEXT && ptr->lft->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(U_OPER, ptr->lft->lft, ptr->rgt->lft), ZN); break; } /* NEW : F X p == X F p */ if (ptr->lft->ntyp == TRUE && ptr->rgt->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(U_OPER, True, ptr->rgt->lft), ZN); break; } #endif /* NEW : F G F p == G F p */ if (ptr->lft->ntyp == TRUE && ptr->rgt->ntyp == V_OPER && ptr->rgt->lft->ntyp == FALSE && ptr->rgt->rgt->ntyp == U_OPER && ptr->rgt->rgt->lft->ntyp == TRUE) { ptr = ptr->rgt; break; } /* NEW */ if (ptr->lft->ntyp != TRUE && implies(push_negation(tl_nn(NOT, dupnode(ptr->rgt), ZN)), ptr->lft)) { ptr->lft = True; break; } break; case V_OPER: if (ptr->rgt->ntyp == FALSE || ptr->rgt->ntyp == TRUE || ptr->lft->ntyp == TRUE) { ptr = ptr->rgt; break; } if (implies(ptr->rgt, ptr->lft)) { /* p V p = p */ ptr = ptr->rgt; break; } /* F V (p V q) == F V q */ if (ptr->lft->ntyp == FALSE && ptr->rgt->ntyp == V_OPER) { ptr->rgt = ptr->rgt->rgt; break; } #ifdef NXT /* NEW : G X p == X G p */ if (ptr->lft->ntyp == FALSE && ptr->rgt->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(V_OPER, False, ptr->rgt->lft), ZN); break; } #endif /* NEW : G F G p == F G p */ if (ptr->lft->ntyp == FALSE && ptr->rgt->ntyp == U_OPER && ptr->rgt->lft->ntyp == TRUE && ptr->rgt->rgt->ntyp == V_OPER && ptr->rgt->rgt->lft->ntyp == FALSE) { ptr = ptr->rgt; break; } /* NEW */ if (ptr->rgt->ntyp == V_OPER && implies(ptr->rgt->lft, ptr->lft)) { ptr = ptr->rgt; break; } /* NEW */ if (ptr->lft->ntyp != FALSE && implies(ptr->lft, push_negation(tl_nn(NOT, dupnode(ptr->rgt), ZN)))) { ptr->lft = False; break; } break; #ifdef NXT case NEXT: /* NEW : X G F p == G F p */ if (ptr->lft->ntyp == V_OPER && ptr->lft->lft->ntyp == FALSE && ptr->lft->rgt->ntyp == U_OPER && ptr->lft->rgt->lft->ntyp == TRUE) { ptr = ptr->lft; break; } /* NEW : X F G p == F G p */ if (ptr->lft->ntyp == U_OPER && ptr->lft->lft->ntyp == TRUE && ptr->lft->rgt->ntyp == V_OPER && ptr->lft->rgt->lft->ntyp == FALSE) { ptr = ptr->lft; break; } break; #endif case IMPLIES: if (implies(ptr->lft, ptr->rgt)) { ptr = True; break; } ptr = tl_nn(OR, Not(ptr->lft), ptr->rgt); ptr = rewrite(ptr); break; case EQUIV: if (implies(ptr->lft, ptr->rgt) && implies(ptr->rgt, ptr->lft)) { ptr = True; break; } a = rewrite(tl_nn(AND, dupnode(ptr->lft), dupnode(ptr->rgt))); b = rewrite(tl_nn(AND, Not(ptr->lft), Not(ptr->rgt))); ptr = tl_nn(OR, a, b); ptr = rewrite(ptr); break; case AND: /* p && (q U p) = p */ if (ptr->rgt->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->lft; break; } if (ptr->lft->ntyp == U_OPER && isequal(ptr->lft->rgt, ptr->rgt)) { ptr = ptr->rgt; break; } /* p && (q V p) == q V p */ if (ptr->rgt->ntyp == V_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->rgt; break; } if (ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt)) { ptr = ptr->lft; break; } /* (p U q) && (r U q) = (p && r) U q*/ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft->rgt)) { ptr = tl_nn(U_OPER, tl_nn(AND, ptr->lft->lft, ptr->rgt->lft), ptr->lft->rgt); break; } /* (p V q) && (p V r) = p V (q && r) */ if (ptr->rgt->ntyp == V_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->rgt->lft, ptr->lft->lft)) { ptr = tl_nn(V_OPER, ptr->rgt->lft, tl_nn(AND, ptr->lft->rgt, ptr->rgt->rgt)); break; } #ifdef NXT /* X p && X q == X (p && q) */ if (ptr->rgt->ntyp == NEXT && ptr->lft->ntyp == NEXT) { ptr = tl_nn(NEXT, tl_nn(AND, ptr->rgt->lft, ptr->lft->lft), ZN); break; } #endif /* (p V q) && (r U q) == p V q */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = ptr->lft; break; } if (isequal(ptr->lft, ptr->rgt) /* (p && p) == p */ || ptr->rgt->ntyp == FALSE /* (p && F) == F */ || ptr->lft->ntyp == TRUE /* (T && p) == p */ || implies(ptr->rgt, ptr->lft))/* NEW */ { ptr = ptr->rgt; break; } if (ptr->rgt->ntyp == TRUE /* (p && T) == p */ || ptr->lft->ntyp == FALSE /* (F && p) == F */ || implies(ptr->lft, ptr->rgt))/* NEW */ { ptr = ptr->lft; break; } /* NEW : F G p && F G q == F G (p && q) */ if (ptr->lft->ntyp == U_OPER && ptr->lft->lft->ntyp == TRUE && ptr->lft->rgt->ntyp == V_OPER && ptr->lft->rgt->lft->ntyp == FALSE && ptr->rgt->ntyp == U_OPER && ptr->rgt->lft->ntyp == TRUE && ptr->rgt->rgt->ntyp == V_OPER && ptr->rgt->rgt->lft->ntyp == FALSE) { ptr = tl_nn(U_OPER, True, tl_nn(V_OPER, False, tl_nn(AND, ptr->lft->rgt->rgt, ptr->rgt->rgt->rgt))); break; } /* NEW */ if (implies(ptr->lft, push_negation(tl_nn(NOT, dupnode(ptr->rgt), ZN))) || implies(ptr->rgt, push_negation(tl_nn(NOT, dupnode(ptr->lft), ZN)))) { ptr = False; break; } break; case OR: /* p || (q U p) == q U p */ if (ptr->rgt->ntyp == U_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->rgt; break; } /* p || (q V p) == p */ if (ptr->rgt->ntyp == V_OPER && isequal(ptr->rgt->rgt, ptr->lft)) { ptr = ptr->lft; break; } /* (p U q) || (p U r) = p U (q || r) */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == U_OPER && isequal(ptr->rgt->lft, ptr->lft->lft)) { ptr = tl_nn(U_OPER, ptr->rgt->lft, tl_nn(OR, ptr->lft->rgt, ptr->rgt->rgt)); break; } if (isequal(ptr->lft, ptr->rgt) /* (p || p) == p */ || ptr->rgt->ntyp == FALSE /* (p || F) == p */ || ptr->lft->ntyp == TRUE /* (T || p) == T */ || implies(ptr->rgt, ptr->lft))/* NEW */ { ptr = ptr->lft; break; } if (ptr->rgt->ntyp == TRUE /* (p || T) == T */ || ptr->lft->ntyp == FALSE /* (F || p) == p */ || implies(ptr->lft, ptr->rgt))/* NEW */ { ptr = ptr->rgt; break; } /* (p V q) || (r V q) = (p || r) V q */ if (ptr->rgt->ntyp == V_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = tl_nn(V_OPER, tl_nn(OR, ptr->lft->lft, ptr->rgt->lft), ptr->rgt->rgt); break; } /* (p V q) || (r U q) == r U q */ if (ptr->rgt->ntyp == U_OPER && ptr->lft->ntyp == V_OPER && isequal(ptr->lft->rgt, ptr->rgt->rgt)) { ptr = ptr->rgt; break; } /* NEW : G F p || G F q == G F (p || q) */ if (ptr->lft->ntyp == V_OPER && ptr->lft->lft->ntyp == FALSE && ptr->lft->rgt->ntyp == U_OPER && ptr->lft->rgt->lft->ntyp == TRUE && ptr->rgt->ntyp == V_OPER && ptr->rgt->lft->ntyp == FALSE && ptr->rgt->rgt->ntyp == U_OPER && ptr->rgt->rgt->lft->ntyp == TRUE) { ptr = tl_nn(V_OPER, False, tl_nn(U_OPER, True, tl_nn(OR, ptr->lft->rgt->rgt, ptr->rgt->rgt->rgt))); break; } /* NEW */ if (implies(push_negation(tl_nn(NOT, dupnode(ptr->rgt), ZN)), ptr->lft) || implies(push_negation(tl_nn(NOT, dupnode(ptr->lft), ZN)), ptr->rgt)) { ptr = True; break; } break; } return ptr; }
/* SUPER ROUTES */ void mMain::s_locale(){ tr.setLocale(locale()); rewrite(route.get("1","/")); }
int main (int argc, string *argv) { int getopt_return_val; int option_index = 0; name_program = xbasename(argv[0]); if (!strcmp(name_program, "ofm2opl") || !strcmp(name_program, "OFM2OPL.EXE")) { program = PROG_OFM2OPL; name_help = OFM2OPLHELP; name_program = "ofm2opl"; name_msg = "This is ofm2opl, Version 2.0"; no_files = 2; files[0] = &name_ofm; files[1] = &name_opl; suffixes[0] = "ofm"; suffixes[1] = "opl"; full_suffixes[0] = ".ofm"; full_suffixes[1] = ".opl"; } else if (!strcmp(name_program, "opl2ofm") || !strcmp(name_program, "OPL2OFM.EXE")) { program = PROG_OPL2OFM; name_help = OPL2OFMHELP; name_program = "opl2ofm"; name_msg = "This is opl2ofm, Version 2.0"; no_files = 2; files[0] = &name_opl; files[1] = &name_ofm; suffixes[0] = "opl"; suffixes[1] = "ofm"; full_suffixes[0] = ".opl"; full_suffixes[1] = ".ofm"; } else if (!strcmp(name_program, "ovp2ovf") || !strcmp(name_program, "OVP2OVF.EXE")) { program = PROG_OVP2OVF; name_help = OVP2OVFHELP; name_program = "ovp2ovf"; name_msg = "This is ovp2ovf, Version 2.0"; no_files = 3; files[0] = &name_ovp; files[1] = &name_ovf; files[2] = &name_ofm; suffixes[0] = "ovp"; suffixes[1] = "ovf"; suffixes[2] = "ofm"; full_suffixes[0] = ".ovp"; full_suffixes[1] = ".ovf"; full_suffixes[2] = ".ofm"; } else if (!strcmp(name_program, "ovf2ovp") || !strcmp(name_program, "OVF2OVP.EXE")) { program = PROG_OVF2OVP; name_help = OVF2OVPHELP; name_program = "ovf2ovp"; name_msg = "This is ovf2ovp, Version 2.0"; no_files = 3; files[0] = &name_ovf; files[1] = &name_ofm; files[2] = &name_ovp; suffixes[0] = "ovf"; suffixes[1] = "ofm"; suffixes[2] = "ovp"; full_suffixes[0] = ".ovf"; full_suffixes[1] = ".ofm"; full_suffixes[2] = ".ovp"; } else { fprintf(stderr , "Unrecognized program: %s\n", name_program); fprintf(stderr , "This binary supports ofm2opl, opl2ofm, ovf2ovp, and ovp2ovf\n"); exit(1); } kpse_set_program_name(name_program, NULL); kpse_init_prog(uppercasify(name_program), 0, nil, nil); do { getopt_return_val = getopt_long_only(argc, argv, "", long_options, &option_index) ; if (getopt_return_val == -1) { ; } else if ( getopt_return_val == 63 ) { usage (name_program); } else if (!strcmp(long_options[option_index].name, "help")) { usagehelp (name_help, NULL); } else if (!strcmp(long_options[option_index ].name, "version")) { printversionandexit(name_msg, nil, "J. Plaice, Y. Haralambous, D.E. Knuth", nil); } else if (!strcmp(long_options[option_index ].name, "char-format")) { if (!strcmp(optarg, "ascii")) char_format = CHAR_CODE_ASCII; else if (!strcmp(optarg, "num")) char_format = CHAR_CODE_NUM; else warning_s("Bad character code format (%s)", optarg); } else if (!strcmp(long_options[option_index ].name, "num-format")) { if (!strcmp(optarg, "hex")) num_format = NUM_CODE_HEX; else if (!strcmp(optarg, "octal")) num_format = NUM_CODE_OCTAL; else warning_s("Bad number code format (%s)", optarg); } else if (!strcmp(long_options[option_index ].name, "text-format")) { if (!strcmp(optarg, "upper")) text_format = TEXT_CODE_UPPER; else if (!strcmp(optarg, "mixed")) text_format = TEXT_CODE_MIXED; else warning_s("Bad text code format (%s)", optarg); } } while (getopt_return_val != -1); if (((argc-optind) > no_files) || ((argc-optind) < 1)) { fprintf(stderr , "%s: %s\n", name_program, no_files == 2 ? "Need one or two file arguments." : "Need one to three file arguments."); usage (name_program); } *(files[0]) = extend_filename(cmdline(optind) , suffixes[0]); if (optind+2 <= argc) { *(files[1]) = extend_filename(cmdline(optind+1) , suffixes[1]); if (no_files == 3) { if (optind+3 <= argc) { *(files[2]) = extend_filename(cmdline(optind+2) , suffixes[2]); } else if (program == PROG_OVP2OVF) { *(files[2]) = extend_filename(cmdline(optind+1), suffixes[2]); } } } else if (program != PROG_OFM2OPL) { *(files[1]) = basenamechangesuffix(*(files[0]), full_suffixes[0], full_suffixes[1]); if ((no_files == 3) && (program == PROG_OVP2OVF)) { *(files[2]) = basenamechangesuffix(*(files[0]), full_suffixes[0], full_suffixes[2]); } } switch(program) { case PROG_OFM2OPL: { file_ofm = kpse_open_file(name_ofm, kpse_ofm_format); read_in_whole(&ofm, &length_ofm, file_ofm, name_ofm); (void)fclose(file_ofm); if (name_opl==NULL) file_opl = stdout; else rewrite(file_opl, name_opl); file_output = file_opl; parse_ofm(FALSE); break; } case PROG_OVF2OVP: { file_ovf = kpse_open_file(name_ovf, kpse_ovf_format); read_in_whole(&ovf, &length_ovf, file_ovf, name_ovf); (void)fclose(file_ovf); file_ofm = kpse_open_file(name_ofm, kpse_ofm_format); read_in_whole(&ofm, &length_ofm, file_ofm, name_ofm); (void)fclose(file_ofm); if (name_ovp==NULL) file_ovp = stdout; else rewrite(file_ovp, name_ovp); file_output = file_ovp; parse_ofm(TRUE); break; } case PROG_OPL2OFM: { file_opl = kpse_open_file(name_opl, kpse_opl_format); rewritebin(file_ofm, name_ofm); init_tables(); yyin = file_opl; (void)yyparse(); output_ofm_file(); (void)fclose(file_ofm); break; } case PROG_OVP2OVF: { file_ovp = kpse_open_file(name_ovp, kpse_ovp_format); rewritebin(file_ovf, name_ovf); rewritebin(file_ofm, name_ofm); init_tables(); yyin = file_ovp; (void)yyparse(); output_ofm_file(); /*(void)fclose(file_ofm);*/ output_ovf_file(); (void)fclose(file_ovf); break; } default: {exit(1);} } exit(0); }