/* * file_init -- * Start editing a file, based on the FREF structure. If successsful, * let go of any previous file. Don't release the previous file until * absolutely sure we have the new one. * * PUBLIC: int file_init __P((SCR *, FREF *, char *, int)); */ int file_init(SCR *sp, FREF *frp, char *rcv_name, int flags) { EXF *ep; struct stat sb; size_t psize; int fd, exists, open_err, readonly, stolen; char *oname, tname[MAXPATHLEN]; stolen = open_err = readonly = 0; /* * If the file is a recovery file, let the recovery code handle it. * Clear the FR_RECOVER flag first -- the recovery code does set up, * and then calls us! If the recovery call fails, it's probably * because the named file doesn't exist. So, move boldly forward, * presuming that there's an error message the user will get to see. */ if (F_ISSET(frp, FR_RECOVER)) { F_CLR(frp, FR_RECOVER); return (rcv_read(sp, frp)); } /* * Required FRP initialization; the only flag we keep is the * cursor information. */ F_CLR(frp, ~FR_CURSORSET); /* * Scan the user's path to find the file that we're going to * try and open. */ if (file_spath(sp, frp, &sb, &exists)) return (1); /* * Check whether we already have this file opened in some * other screen. */ if (exists) { EXF *exfp; for (exfp = sp->gp->exfq.cqh_first; exfp != (EXF *)&sp->gp->exfq; exfp = exfp->q.cqe_next) { if (exfp->mdev == sb.st_dev && exfp->minode == sb.st_ino && (exfp != sp->ep || exfp->refcnt > 1)) { ep = exfp; goto postinit; } } } /* * Required EXF initialization: * Flush the line caches. * Default recover mail file fd to -1. * Set initial EXF flag bits. */ CALLOC_RET(sp, ep, EXF *, 1, sizeof(EXF)); CIRCLEQ_INIT(&ep->scrq); sp->c_lno = ep->c_nlines = OOBLNO; ep->rcv_fd = ep->fcntl_fd = -1; F_SET(ep, F_FIRSTMODIFY); /* * If no name or backing file, for whatever reason, create a backing * temporary file, saving the temp file name so we can later unlink * it. If the user never named this file, copy the temporary file name * to the real name (we display that until the user renames it). */ oname = frp->name; if (LF_ISSET(FS_OPENERR) || oname == NULL || !exists) { if (opts_empty(sp, O_TMP_DIRECTORY, 0)) goto err; (void)snprintf(tname, sizeof(tname), "%s/vi.XXXXXX", O_STR(sp, O_TMP_DIRECTORY)); if ((fd = mkstemp(tname)) == -1) { msgq(sp, M_SYSERR, "237|Unable to create temporary file"); goto err; } (void)close(fd); if (frp->name == NULL) F_SET(frp, FR_TMPFILE); if ((frp->tname = strdup(tname)) == NULL || (frp->name == NULL && (frp->name = strdup(tname)) == NULL)) { if (frp->tname != NULL) { free(frp->tname); } msgq(sp, M_SYSERR, NULL); (void)unlink(tname); goto err; } oname = frp->tname; psize = 1024; if (!LF_ISSET(FS_OPENERR)) F_SET(frp, FR_NEWFILE); time(&ep->mtime); } else { /* * XXX * A seat of the pants calculation: try to keep the file in * 15 pages or less. Don't use a page size larger than 10K * (vi should have good locality) or smaller than 1K. */ psize = ((sb.st_size / 15) + 1023) / 1024; if (psize > 10) psize = 10; if (psize == 0) psize = 1; psize *= 1024; F_SET(ep, F_DEVSET); ep->mdev = sb.st_dev; ep->minode = sb.st_ino; ep->mtime = sb.st_mtime; if (!S_ISREG(sb.st_mode)) msgq_str(sp, M_ERR, oname, "238|Warning: %s is not a regular file"); } /* Set up recovery. */ if (rcv_name == NULL) { /* ep->rcv_path NULL if rcv_tmp fails */ rcv_tmp(sp, ep, frp->name); } else { if ((ep->rcv_path = strdup(rcv_name)) == NULL) { msgq(sp, M_SYSERR, NULL); goto err; } F_SET(ep, F_MODIFIED); } if (db_setup(sp, ep)) goto err; /* Open a db structure. */ if ((sp->db_error = db_create(&ep->db, 0, 0)) != 0) { msgq(sp, M_DBERR, "db_create"); goto err; } ep->db->set_re_delim(ep->db, '\n'); /* Always set. */ ep->db->set_pagesize(ep->db, psize); ep->db->set_flags(ep->db, DB_RENUMBER | DB_SNAPSHOT); if (rcv_name == NULL) ep->db->set_re_source(ep->db, oname); /* * Don't let db use mmap when using fcntl for locking */ #ifdef HAVE_LOCK_FCNTL #define NOMMAPIFFCNTL DB_NOMMAP #else #define NOMMAPIFFCNTL 0 #endif #define _DB_OPEN_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO, ((rcv_name == 0) ? DB_TRUNCATE : 0) | VI_DB_THREAD | NOMMAPIFFCNTL, _DB_OPEN_MODE)) != 0) { msgq_str(sp, M_DBERR, rcv_name == NULL ? oname : rcv_name, "%s"); /* * !!! * Historically, vi permitted users to edit files that couldn't * be read. This isn't useful for single files from a command * line, but it's quite useful for "vi *.c", since you can skip * past files that you can't read. */ ep->db = NULL; /* Don't close it; it wasn't opened */ if (LF_ISSET(FS_OPENERR)) goto err; open_err = 1; goto oerr; } /* re_source is loaded into the database. * Close it and reopen it in the environment. */ if ((sp->db_error = ep->db->close(ep->db, 0))) { msgq(sp, M_DBERR, "close"); goto err; } if ((sp->db_error = db_create(&ep->db, ep->env, 0)) != 0) { msgq(sp, M_DBERR, "db_create 2"); goto err; } if ((sp->db_error = db_open(ep->db, ep->rcv_path, DB_RECNO, VI_DB_THREAD | NOMMAPIFFCNTL, _DB_OPEN_MODE)) != 0) { msgq_str(sp, M_DBERR, ep->rcv_path, "%s"); goto err; } /* * Do the remaining things that can cause failure of the new file, * mark and logging initialization. */ if (mark_init(sp, ep) || log_init(sp, ep)) goto err; postinit: /* * Set the alternate file name to be the file we're discarding. * * !!! * Temporary files can't become alternate files, so there's no file * name. This matches historical practice, although it could only * happen in historical vi as the result of the initial command, i.e. * if vi was executed without a file name. */ if (LF_ISSET(FS_SETALT)) set_alt_name(sp, sp->frp == NULL || F_ISSET(sp->frp, FR_TMPFILE) ? NULL : sp->frp->name); /* * Close the previous file; if that fails, close the new one and run * for the border. * * !!! * There's a nasty special case. If the user edits a temporary file, * and then does an ":e! %", we need to re-initialize the backing * file, but we can't change the name. (It's worse -- we're dealing * with *names* here, we can't even detect that it happened.) Set a * flag so that the file_end routine ignores the backing information * of the old file if it happens to be the same as the new one. * * !!! * Side-effect: after the call to file_end(), sp->frp may be NULL. */ if (sp->ep != NULL) { F_SET(frp, FR_DONTDELETE); if (file_end(sp, NULL, LF_ISSET(FS_FORCE))) { (void)file_end(sp, ep, 1); goto err; } sp->ep = NULL; F_CLR(frp, FR_DONTDELETE); } /* * Lock the file; if it's a recovery file, it should already be * locked. Note, we acquire the lock after the previous file * has been ended, so that we don't get an "already locked" error * for ":edit!". * * XXX * While the user can't interrupt us between the open and here, * there's a race between the dbopen() and the lock. Not much * we can do about it. * * XXX * We don't make a big deal of not being able to lock the file. As * locking rarely works over NFS, and often fails if the file was * mmap(2)'d, it's far too common to do anything like print an error * message, let alone make the file readonly. At some future time, * when locking is a little more reliable, this should change to be * an error. */ if (rcv_name == NULL && ep->refcnt == 0) { if ((ep->fd = open(oname, O_RDWR)) == -1) goto no_lock; switch (file_lock(sp, oname, &ep->fcntl_fd, ep->fd, 1)) { case LOCK_FAILED: no_lock: F_SET(frp, FR_UNLOCKED); break; case LOCK_UNAVAIL: readonly = 1; msgq_str(sp, M_INFO, oname, "239|%s already locked, session is read-only"); break; case LOCK_SUCCESS: break; } } /* * Historically, the readonly edit option was set per edit buffer in * vi, unless the -R command-line option was specified or the program * was executed as "view". (Well, to be truthful, if the letter 'w' * occurred anywhere in the program name, but let's not get into that.) * So, the persistant readonly state has to be stored in the screen * structure, and the edit option value toggles with the contents of * the edit buffer. If the persistant readonly flag is set, set the * readonly edit option. * * Otherwise, try and figure out if a file is readonly. This is a * dangerous thing to do. The kernel is the only arbiter of whether * or not a file is writeable, and the best that a user program can * do is guess. Obvious loopholes are files that are on a file system * mounted readonly (access catches this one on a few systems), or * alternate protection mechanisms, ACL's for example, that we can't * portably check. Lots of fun, and only here because users whined. * * !!! * Historic vi displayed the readonly message if none of the file * write bits were set, or if an an access(2) call on the path * failed. This seems reasonable. If the file is mode 444, root * users may want to know that the owner of the file did not expect * it to be written. * * Historic vi set the readonly bit if no write bits were set for * a file, even if the access call would have succeeded. This makes * the superuser force the write even when vi expects that it will * succeed. I'm less supportive of this semantic, but it's historic * practice and the conservative approach to vi'ing files as root. * * It would be nice if there was some way to update this when the user * does a "^Z; chmod ...". The problem is that we'd first have to * distinguish between readonly bits set because of file permissions * and those set for other reasons. That's not too hard, but deciding * when to reevaluate the permissions is trickier. An alternative * might be to turn off the readonly bit if the user forces a write * and it succeeds. * * XXX * Access(2) doesn't consider the effective uid/gid values. This * probably isn't a problem for vi when it's running standalone. */ if (readonly || F_ISSET(sp, SC_READONLY) || (!F_ISSET(frp, FR_NEWFILE) && (!(sb.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) || access(frp->name, W_OK)))) O_SET(sp, O_READONLY); else O_CLR(sp, O_READONLY); /* Switch... */ ++ep->refcnt; CIRCLEQ_INSERT_HEAD(&ep->scrq, sp, eq); sp->ep = ep; sp->frp = frp; /* Set the initial cursor position, queue initial command. */ file_cinit(sp); /* Report conversion errors again. */ F_CLR(sp, SC_CONV_ERROR); /* Redraw the screen from scratch, schedule a welcome message. */ F_SET(sp, SC_SCR_REFORMAT | SC_STATUS); if (frp->lno == OOBLNO) F_SET(sp, SC_SCR_TOP); /* Append into the chain of file structures. */ if (ep->refcnt == 1) CIRCLEQ_INSERT_TAIL(&sp->gp->exfq, ep, q); return (0); err: if (frp->name != NULL) { free(frp->name); frp->name = NULL; } if (frp->tname != NULL) { (void)unlink(frp->tname); free(frp->tname); frp->tname = NULL; } oerr: if (F_ISSET(ep, F_RCV_ON)) (void)unlink(ep->rcv_path); if (ep->rcv_path != NULL) { free(ep->rcv_path); ep->rcv_path = NULL; } if (ep->db != NULL) { (void)ep->db->close(ep->db, DB_NOSYNC); ep->db = NULL; } free(ep); return (open_err && !LF_ISSET(FS_OPENERR) ? file_init(sp, frp, rcv_name, flags | FS_OPENERR) : 1); }
int main(int argc, char *argv[]) { void *buf; _xcc_status cc; unsigned short count_read; unsigned short count_written; unsigned short count_xferred; int ferr; short filenum; short lasterr; int inx; int loop = 10; char my_name[BUFSIZ]; bool nowait = false; int nid; char *p; int pid; char recv_buffer[BUFSIZ]; char send_buffer[BUFSIZ]; SB_Tag_Type tag; short tfilenum; int tm_seq; int timeout = -1; MS_Mon_Transid_Type transid; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-nowait", TA_Bool, TA_NOMAX, &nowait }, { "-print", TA_Bool, TA_NOMAX, &print }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; TRANSID_SET_NULL(curr_transid); TRANSID_SET_NULL(exp_trans); ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages TEST_CHK_FEOK(ferr); util_gethostname(my_name, sizeof(my_name)); ferr = msg_mon_trans_register_tmlib(tmlib); TEST_CHK_FEOK(ferr); ferr = msg_mon_get_process_info(NULL, &nid, &pid); TEST_CHK_FEOK(ferr); if (client) { ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, nowait ? (short) 1 : (short) 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { ferr = msg_mon_get_tm_seq(&tm_seq); TEST_CHK_FEOK(ferr); if (inx & 1) cc = XSETMODE(filenum, 117, 1, 0, NULL); // suppress else cc = XSETMODE(filenum, 117, 0, 0, NULL); // normal TEST_CHK_CCEQ(cc); ferr = XFILE_GETINFO_(-1, &lasterr, NULL, 0, NULL, NULL, NULL); assert(lasterr == XZFIL_ERR_OK); sprintf(send_buffer, "hello, greetings from %s, inx=%d, trans=%d", my_name, inx, tm_seq); if (print) printf("client enlist, transid=%d\n", tm_seq); TRANSID_SET_SEQ(transid, tm_seq); trans_set_curr(transid); if ((inx & 1) == 0) { ferr = msg_mon_trans_enlist(nid, pid, transid); TEST_CHK_FEOK(ferr); } if ((inx & 1) == 0) fun_set(TMLIB_FUN_GET_TX, TMLIB_FUN_REINSTATE_TX); else fun_set(-1, -1); trans_set(transid); cc = XWRITEREADX(filenum, send_buffer, (short) (strlen(send_buffer) + 1), BUFSIZ, &count_read, 0); if (nowait) { TEST_CHK_CCEQ(cc); tfilenum = filenum; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); } TEST_CHK_CCEQ(cc); fun_check(-1); if (print) printf("client end, transid=%d\n", tm_seq); if ((inx & 1) == 0) { ferr = msg_mon_trans_end(nid, pid, transid); TEST_CHK_FEOK(ferr); TRANSID_SET_NULL(transid); trans_set_curr(transid); // no more trans } printf("%s\n", send_buffer); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, nowait ? (short) 1 : (short) 0, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { if ((inx & 1) == 0) fun_set(TMLIB_FUN_REG_TX, -1); else fun_set(-1, -1); cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); if (nowait) { tfilenum = filenum; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); } if (inx & 1) { TRANSID_SET_NULL(transid); } else { p = &recv_buffer[strlen(recv_buffer)]; while ((p > recv_buffer) && (*p != '=')) p--; if (*p == '=') { p++; sscanf(p, "%d", &tm_seq); TRANSID_SET_SEQ(transid, tm_seq); } else TRANSID_SET_NULL(transid); } if (inx & 1) { MS_Mon_Transid_Type ltransid; TRANSID_SET_NULL(ltransid); trans_set_curr(ltransid); } trans_set(transid); trans_check(curr_transid); fun_check(-1); if ((inx & 1) == 0) fun_set(TMLIB_FUN_CLEAR_TX, -1); else fun_set(-1, -1); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (short) (strlen(recv_buffer) + 1); cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_FEOK(ferr); fun_check(-1); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
int main(int argc, char *argv[]) { void *buf; _xcc_status cc; bool client = false; unsigned short count_read; unsigned short count_written; unsigned short count_xferred; int ferr; short filenum; int inx; int loop = 10; char recv_buffer[BUFSIZ]; char send_buffer[BUFSIZ]; SB_Tag_Type tag; short tfilenum; int timeout = -1; bool verbose = false; int xinx; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-v", TA_Bool, TA_NOMAX, &verbose }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages TEST_CHK_FEOK(ferr); if (client) { ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, 1, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "inx=%d, tag=%d", inx, inx); cc = XWRITEREADX(filenum, send_buffer, (short) (strlen(send_buffer) + 1), BUFSIZ, &count_read, inx); TEST_CHK_CCEQ(cc); if (inx < (loop - 1)) { cc = XCANCELREQ(filenum, inx); TEST_CHK_CCEQ(cc); if (verbose) printf("client cancelled inx=%d\n", inx); } else { printf("client waiting response inx=%d\n", inx); tfilenum = filenum; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); assert(tag == inx); printf("%s\n", send_buffer); } } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); printf("if there were no asserts, all is well\n"); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 1, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 1); TEST_CHK_CCEQ(cc); tfilenum = filenum; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); count_read = (short) (strlen(recv_buffer) + 1); sscanf(recv_buffer, "inx=%d", &xinx); if (verbose) printf("server replying, server inx=%d, client inx=%d, %s\n", inx, xinx, recv_buffer); inx = xinx; cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } if (verbose) printf("server closing file inx=%d\n", inx); ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
int main(int argc, char *argv[]) { bool abort1 = false; bool abort2 = false; void *buf; _xcc_status cc; bool client = false; int count_read; int count_written; int count_xferred; int dsize = 1024; int ferr; short filenum; int inx; int loop = 10; short mt; char my_name[BUFSIZ]; bool verbose = false; SB_Tag_Type tag; short tfilenum; int timeout = -1; TAD zargs[] = { { "-abort1", TA_Bool, TA_NOMAX, &abort1 }, { "-abort2", TA_Bool, TA_NOMAX, &abort2 }, { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-v", TA_Bool, TA_NOMAX, &verbose }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); ferr = msg_mon_get_my_process_name(my_name, BUFSIZ); util_check("msg_mon_get_my_process_name", ferr); if (client) { ferr = BFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, (short) 1, // nowait 0, 0, 0, 0, NULL); if (verbose) printf("client open ferr=%d\n", ferr); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); cc = BWRITEREADX(filenum, send_buffer, (unsigned short) (strlen(send_buffer) + 1), // cast 0, &count_read, 0); if (verbose) printf("client wr cc=%d\n", cc); TEST_CHK_CCEQ(cc); tfilenum = -2; cc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); if (verbose) printf("client awaitiox cc=%d, fn=%d\n", cc, tfilenum); if (abort1) { if (_xstatus_ne(cc)) { sleep(1); inx--; continue; } } else { TEST_CHK_CCEQ(cc); } printf("%s\n", send_buffer); } } else { ferr = BFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, (short) 0, 1, 0, // sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); if (abort1) { } else if (abort2) { loop -= 2; } else { loop += 2; } for (inx = 0; inx < loop; inx++) { if (abort1 && (inx == 3)) util_abort_core_free(); cc = BREADUPDATEX(filenum, recv_buffer, (int) dsize, // cast &count_read, 0); if (verbose) { memcpy(&mt, recv_buffer, sizeof(mt)); printf("server cc=%d, mt=%d\n", cc, mt); } cc = BREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } } if (client) { ferr = BFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { ferr = BFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
/* * ex_read -- :read [file] * :read [!cmd] * Read from a file or utility. * * !!! * Historical vi wouldn't undo a filter read, for no apparent reason. * * PUBLIC: int ex_read __P((SCR *, EXCMD *)); */ int ex_read(SCR *sp, EXCMD *cmdp) { enum { R_ARG, R_EXPANDARG, R_FILTER } which; struct stat sb; CHAR_T *arg; char *name; size_t nlen; EX_PRIVATE *exp; FILE *fp; FREF *frp; GS *gp; MARK rm; db_recno_t nlines; size_t arglen; int argc, rval; char *p; char *np; gp = sp->gp; /* * 0 args: read the current pathname. * 1 args: check for "read !arg". */ switch (cmdp->argc) { case 0: which = R_ARG; break; case 1: arg = cmdp->argv[0]->bp; arglen = cmdp->argv[0]->len; if (*arg == '!') { ++arg; --arglen; which = R_FILTER; /* Secure means no shell access. */ if (O_ISSET(sp, O_SECURE)) { ex_wemsg(sp, cmdp->cmd->name, EXM_SECURE_F); return (1); } } else which = R_EXPANDARG; break; default: abort(); /* NOTREACHED */ } /* Load a temporary file if no file being edited. */ if (sp->ep == NULL) { if ((frp = file_add(sp, NULL)) == NULL) return (1); if (file_init(sp, frp, NULL, 0)) return (1); } switch (which) { case R_FILTER: /* * File name and bang expand the user's argument. If * we don't get an additional argument, it's illegal. */ argc = cmdp->argc; if (argv_exp1(sp, cmdp, arg, arglen, 1)) return (1); if (argc == cmdp->argc) { ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE); return (1); } argc = cmdp->argc - 1; /* Set the last bang command. */ exp = EXP(sp); if (exp->lastbcomm != NULL) free(exp->lastbcomm); if ((exp->lastbcomm = v_wstrdup(sp, cmdp->argv[argc]->bp, cmdp->argv[argc]->len)) == NULL) { msgq(sp, M_SYSERR, NULL); return (1); } /* * Vi redisplayed the user's argument if it changed, ex * always displayed a !, plus the user's argument if it * changed. */ if (F_ISSET(sp, SC_VI)) { if (F_ISSET(cmdp, E_MODIFY)) (void)vs_update(sp, "!", cmdp->argv[argc]->bp); } else { if (F_ISSET(cmdp, E_MODIFY)) (void)ex_printf(sp, "!%s\n", cmdp->argv[argc]->bp); else (void)ex_puts(sp, "!\n"); (void)ex_fflush(sp); } /* * Historically, filter reads as the first ex command didn't * wait for the user. If SC_SCR_EXWROTE not already set, set * the don't-wait flag. */ if (!F_ISSET(sp, SC_SCR_EXWROTE)) F_SET(sp, SC_EX_WAIT_NO); /* * Switch into ex canonical mode. The reason to restore the * original terminal modes for read filters is so that users * can do things like ":r! cat /dev/tty". * * !!! * We do not output an extra <newline>, so that we don't touch * the screen on a normal read. */ if (F_ISSET(sp, SC_VI)) { if (gp->scr_screen(sp, SC_EX)) { ex_wemsg(sp, cmdp->cmd->name, EXM_NOCANON_F); return (1); } /* * !!! * Historically, the read command doesn't switch to * the alternate X11 xterm screen, if doing a filter * read -- don't set SA_ALTERNATE. */ F_SET(sp, SC_SCR_EX | SC_SCR_EXWROTE); } if (ex_filter(sp, cmdp, &cmdp->addr1, NULL, &rm, cmdp->argv[argc]->bp, FILTER_READ)) return (1); /* The filter version of read set the autoprint flag. */ F_SET(cmdp, E_AUTOPRINT); /* * If in vi mode, move to the first nonblank. Might have * switched into ex mode, so saved the original SC_VI value. */ sp->lno = rm.lno; if (F_ISSET(sp, SC_VI)) { sp->cno = 0; (void)nonblank(sp, sp->lno, &sp->cno); } return (0); case R_ARG: name = sp->frp->name; break; case R_EXPANDARG: if (argv_exp2(sp, cmdp, arg, arglen)) return (1); /* * 0 args: impossible. * 1 args: impossible (I hope). * 2 args: read it. * >2 args: object, too many args. * * The 1 args case depends on the argv_sexp() function refusing * to return success without at least one non-blank character. */ switch (cmdp->argc) { case 0: case 1: abort(); /* NOTREACHED */ case 2: INT2CHAR(sp, cmdp->argv[1]->bp, cmdp->argv[1]->len + 1, name, nlen); /* * !!! * Historically, the read and write commands renamed * "unnamed" files, or, if the file had a name, set * the alternate file name. */ if (F_ISSET(sp->frp, FR_TMPFILE) && !F_ISSET(sp->frp, FR_EXNAMED)) { if ((p = strdup(name)) != NULL) { free(sp->frp->name); sp->frp->name = p; } /* * The file has a real name, it's no longer a * temporary, clear the temporary file flags. */ F_CLR(sp->frp, FR_TMPEXIT | FR_TMPFILE); F_SET(sp->frp, FR_NAMECHANGE | FR_EXNAMED); /* Notify the screen. */ (void)sp->gp->scr_rename(sp, sp->frp->name, 1); name = sp->frp->name; } else { set_alt_name(sp, name); name = sp->alt_name; } break; default: ex_wemsg(sp, cmdp->argv[0]->bp, EXM_FILECOUNT); return (1); } break; } /* * !!! * Historically, vi did not permit reads from non-regular files, nor * did it distinguish between "read !" and "read!", so there was no * way to "force" it. We permit reading from named pipes too, since * they didn't exist when the original implementation of vi was done * and they seem a reasonable addition. */ if ((fp = fopen(name, "r")) == NULL || fstat(fileno(fp), &sb)) { msgq_str(sp, M_SYSERR, name, "%s"); return (1); } if (!S_ISFIFO(sb.st_mode) && !S_ISREG(sb.st_mode)) { (void)fclose(fp); msgq(sp, M_ERR, "145|Only regular files and named pipes may be read"); return (1); } /* Try and get a lock. */ if (file_lock(sp, NULL, NULL, fileno(fp), 0) == LOCK_UNAVAIL) msgq(sp, M_ERR, "146|%s: read lock was unavailable", name); rval = ex_readfp(sp, name, fp, &cmdp->addr1, &nlines, 0); /* * In vi, set the cursor to the first line read in, if anything read * in, otherwise, the address. (Historic vi set it to the line after * the address regardless, but since that line may not exist we don't * bother.) * * In ex, set the cursor to the last line read in, if anything read in, * otherwise, the address. */ if (F_ISSET(sp, SC_VI)) { sp->lno = cmdp->addr1.lno; if (nlines) ++sp->lno; } else sp->lno = cmdp->addr1.lno + nlines; return (rval); }
int main(int argc, char *argv[]) { _xcc_status cc; bool client = false; unsigned short count_read; unsigned short count_written; int ferr; short filenumr; short filenums[MAXSRV]; int inxl; int inxs; int loop = 10; int maxsp = 2; bool verbose = false; xzsys_ddl_smsg_def *sys_msg = (xzsys_ddl_smsg_def *) recv_buffer; struct timeval t_elapsed_close; struct timeval t_elapsed_closem1; struct timeval t_elapsed_open; struct timeval t_elapsed_openm1; struct timeval t_start_close; struct timeval t_start_closem1; struct timeval t_start_open; struct timeval t_start_openm1; struct timeval t_stop_close; struct timeval t_stop_closem1; struct timeval t_stop_open; struct timeval t_stop_openm1; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-maxsp", TA_Int, MAXSRV, &maxsp }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-v", TA_Bool, TA_NOMAX, &verbose }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); if (client) { util_time_timer_start(&t_start_open); for (inxs = 0; inxs < maxsp; inxs++) { ferr = XFILE_OPEN_((char *) "$srv", 4, &filenums[inxs], 0, 0, 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); if (inxs == 0) util_time_timer_start(&t_start_openm1); } util_time_timer_stop(&t_stop_open); util_time_timer_stop(&t_stop_openm1); for (inxs = 0; inxs < maxsp; inxs++) { for (inxl = 0; inxl < loop; inxl++) { sprintf(send_buffer, "hello, greetings %d from %s, inx=%d", inxs, my_name, inxl); cc = XWRITEREADX(filenums[inxs], send_buffer, (unsigned short) (strlen(send_buffer) + 1), // cast BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); printf("%s\n", send_buffer); } } util_time_timer_start(&t_start_close); util_time_timer_start(&t_start_closem1); for (inxs = 0; inxs < maxsp; inxs++) { if (inxs == (maxsp - 1)) util_time_timer_stop(&t_stop_closem1); ferr = XFILE_CLOSE_(filenums[inxs], 0); TEST_CHK_FEOK(ferr); } util_time_timer_stop(&t_stop_close); util_time_elapsed(&t_start_open, &t_stop_open, &t_elapsed_open); util_time_elapsed(&t_start_openm1, &t_stop_openm1, &t_elapsed_openm1); util_time_elapsed(&t_start_close, &t_stop_close, &t_elapsed_close); util_time_elapsed(&t_start_closem1, &t_stop_closem1, &t_elapsed_closem1); print_elapsed(" (open)", &t_elapsed_open); print_elapsed(" (open-1st)", &t_elapsed_openm1); print_elapsed(" (close)", &t_elapsed_close); print_elapsed(" (close-lst)", &t_elapsed_closem1); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenumr, 0, 0, 0, 1, 0, // sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); // process opens for (inxs = 0; inxs < maxsp; inxs++) { cc = XREADUPDATEX(filenumr, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCNE(cc); if (verbose) { int mt = sys_msg->u_z_msg.z_msgnumber[0]; printf("inx=%d, type=%d\n", inxs, mt); } cc = XREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } for (inxs = 0; inxs < maxsp; inxs++) { for (inxl = 0; inxl < loop; inxl++) { cc = XREADUPDATEX(filenumr, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (unsigned short) (strlen(recv_buffer) + 1); // cast cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } } // process closes for (inxs = 0; inxs < maxsp; inxs++) { cc = XREADUPDATEX(filenumr, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCNE(cc); if (verbose) { int mt = sys_msg->u_z_msg.z_msgnumber[0]; printf("inx=%d, type=%d\n", inxs, mt); } cc = XREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } ferr = XFILE_CLOSE_(filenumr, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
int main(int argc, char *argv[]) { void *buf; _xcc_status cc; bool client = false; unsigned short count_read; unsigned short count_written; unsigned short count_xferred; int ferr; short filenum; int inx; short lasterr; int loop = 10; char my_name[BUFSIZ]; bool nowait = true; char recv_buffer[BUFSIZ]; char send_buffer[BUFSIZ]; SB_Tag_Type tag; short tfilenum; int timeout; int timeout_count; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages TEST_CHK_FEOK(ferr); util_gethostname(my_name, sizeof(my_name)); if (client) { timeout_count = 0; ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, nowait ? (short) 1 : (short) 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); cc = XWRITEREADX(filenum, send_buffer, (short) (strlen(send_buffer) + 1), BUFSIZ, &count_read, 0); if (nowait) { TEST_CHK_CCEQ(cc); tfilenum = filenum; timeout = 1; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); if (_xstatus_ne(cc)) { timeout_count++; TEST_CHK_CCNE(cc); ferr = XFILE_GETINFO_(filenum, &lasterr, NULL, 0, NULL, NULL, NULL); assert(lasterr == XZFIL_ERR_TIMEDOUT); tfilenum = filenum; timeout = 200; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); } } else { TEST_CHK_CCNE(cc); ferr = XFILE_GETINFO_(-1, &lasterr, NULL, 0, NULL, NULL, NULL); TEST_CHK_FEOK(ferr); assert(lasterr == XZFIL_ERR_TIMEDOUT); } printf("%s\n", send_buffer); } assert(timeout_count); ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 0, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); SB_Thread::Sthr::sleep(30); // cause timeout TEST_CHK_CCEQ(cc); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (short) (strlen(recv_buffer) + 1); cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
/* * editor -- * Main editor routine. * * PUBLIC: int editor __P((GS *, int, char *[])); */ int editor( GS *gp, int argc, char *argv[]) { extern int optind; extern char *optarg; const char *p; EVENT ev; FREF *frp; SCR *sp; size_t len; u_int flags; int ch, flagchk, lflag, secure, startup, readonly, rval, silent; char *tag_f, *wsizearg, path[256]; CHAR_T *w; size_t wlen; /* Initialize the busy routine, if not defined by the screen. */ if (gp->scr_busy == NULL) gp->scr_busy = vs_busy; /* Initialize the message routine, if not defined by the screen. */ if (gp->scr_msg == NULL) gp->scr_msg = vs_msg; gp->catd = (nl_catd)-1; /* Common global structure initialization. */ TAILQ_INIT(gp->dq); TAILQ_INIT(gp->hq); SLIST_INIT(gp->ecq); SLIST_INSERT_HEAD(gp->ecq, &gp->excmd, q); gp->noprint = DEFAULT_NOPRINT; /* Structures shared by screens so stored in the GS structure. */ TAILQ_INIT(gp->frefq); TAILQ_INIT(gp->dcb_store.textq); SLIST_INIT(gp->cutq); SLIST_INIT(gp->seqq); /* Set initial screen type and mode based on the program name. */ readonly = 0; if (!strcmp(gp->progname, "ex") || !strcmp(gp->progname, "nex")) LF_INIT(SC_EX); else { /* Nview, view are readonly. */ if (!strcmp(gp->progname, "nview") || !strcmp(gp->progname, "view")) readonly = 1; /* Vi is the default. */ LF_INIT(SC_VI); } /* Convert old-style arguments into new-style ones. */ if (v_obsolete(gp->progname, argv)) return (1); /* Parse the arguments. */ flagchk = '\0'; tag_f = wsizearg = NULL; lflag = secure = silent = 0; startup = 1; /* Set the file snapshot flag. */ F_SET(gp, G_SNAPSHOT); #ifdef DEBUG while ((ch = getopt(argc, argv, "c:D:eFlRrSsT:t:vw:")) != EOF) #else while ((ch = getopt(argc, argv, "c:eFlRrSst:vw:")) != EOF) #endif switch (ch) { case 'c': /* Run the command. */ /* * XXX * We should support multiple -c options. */ if (gp->c_option != NULL) { v_estr(gp->progname, 0, "only one -c command may be specified."); return (1); } gp->c_option = optarg; break; #ifdef DEBUG case 'D': switch (optarg[0]) { case 's': startup = 0; break; case 'w': attach(gp); break; default: v_estr(gp->progname, 0, "usage: -D requires s or w argument."); return (1); } break; #endif case 'e': /* Ex mode. */ LF_CLR(SC_VI); LF_SET(SC_EX); break; case 'F': /* No snapshot. */ F_CLR(gp, G_SNAPSHOT); break; case 'l': /* Set lisp, showmatch options. */ lflag = 1; break; case 'R': /* Readonly. */ readonly = 1; break; case 'r': /* Recover. */ if (flagchk == 't') { v_estr(gp->progname, 0, "only one of -r and -t may be specified."); return (1); } flagchk = 'r'; break; case 'S': secure = 1; break; case 's': silent = 1; break; #ifdef DEBUG case 'T': /* Trace. */ if ((gp->tracefp = fopen(optarg, "w")) == NULL) { v_estr(gp->progname, errno, optarg); goto err; } (void)fprintf(gp->tracefp, "\n===\ntrace: open %s\n", optarg); break; #endif case 't': /* Tag. */ if (flagchk == 'r') { v_estr(gp->progname, 0, "only one of -r and -t may be specified."); return (1); } if (flagchk == 't') { v_estr(gp->progname, 0, "only one tag file may be specified."); return (1); } flagchk = 't'; tag_f = optarg; break; case 'v': /* Vi mode. */ LF_CLR(SC_EX); LF_SET(SC_VI); break; case 'w': wsizearg = optarg; break; case '?': default: (void)gp->scr_usage(); return (1); } argc -= optind; argv += optind; /* * -s option is only meaningful to ex. * * If not reading from a terminal, it's like -s was specified. */ if (silent && !LF_ISSET(SC_EX)) { v_estr(gp->progname, 0, "-s option is only applicable to ex."); goto err; } if (LF_ISSET(SC_EX) && F_ISSET(gp, G_SCRIPTED)) silent = 1; /* * Build and initialize the first/current screen. This is a bit * tricky. If an error is returned, we may or may not have a * screen structure. If we have a screen structure, put it on a * display queue so that the error messages get displayed. * * !!! * Everything we do until we go interactive is done in ex mode. */ if (screen_init(gp, NULL, &sp)) { if (sp != NULL) TAILQ_INSERT_HEAD(gp->dq, sp, q); goto err; } F_SET(sp, SC_EX); TAILQ_INSERT_HEAD(gp->dq, sp, q); if (v_key_init(sp)) /* Special key initialization. */ goto err; { int oargs[5], *oargp = oargs; if (lflag) { /* Command-line options. */ *oargp++ = O_LISP; *oargp++ = O_SHOWMATCH; } if (readonly) *oargp++ = O_READONLY; if (secure) *oargp++ = O_SECURE; *oargp = -1; /* Options initialization. */ if (opts_init(sp, oargs)) goto err; } if (wsizearg != NULL) { ARGS *av[2], a, b; (void)snprintf(path, sizeof(path), "window=%s", wsizearg); a.bp = (CHAR_T *)path; a.len = strlen(path); b.bp = NULL; b.len = 0; av[0] = &a; av[1] = &b; (void)opts_set(sp, av, NULL); } if (silent) { /* Ex batch mode option values. */ O_CLR(sp, O_AUTOPRINT); O_CLR(sp, O_PROMPT); O_CLR(sp, O_VERBOSE); O_CLR(sp, O_WARN); F_SET(sp, SC_EX_SILENT); } sp->rows = O_VAL(sp, O_LINES); /* Make ex formatting work. */ sp->cols = O_VAL(sp, O_COLUMNS); if (!silent && startup) { /* Read EXINIT, exrc files. */ if (ex_exrc(sp)) goto err; if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) { if (screen_end(sp)) goto err; goto done; } } /* * List recovery files if -r specified without file arguments. * Note, options must be initialized and startup information * read before doing this. */ if (flagchk == 'r' && argv[0] == NULL) { if (rcv_list(sp)) goto err; if (screen_end(sp)) goto err; goto done; } /* * !!! * Initialize the default ^D, ^U scrolling value here, after the * user has had every opportunity to set the window option. * * It's historic practice that changing the value of the window * option did not alter the default scrolling value, only giving * a count to ^D/^U did that. */ sp->defscroll = (O_VAL(sp, O_WINDOW) + 1) / 2; /* * If we don't have a command-line option, switch into the right * editor now, so that we position default files correctly, and * so that any tags file file-already-locked messages are in the * vi screen, not the ex screen. * * XXX * If we have a command-line option, the error message can end * up in the wrong place, but I think that the combination is * unlikely. */ if (gp->c_option == NULL) { F_CLR(sp, SC_EX | SC_VI); F_SET(sp, LF_ISSET(SC_EX | SC_VI)); } /* Open a tag file if specified. */ if (tag_f != NULL) { CHAR2INT(sp, tag_f, strlen(tag_f) + 1, w, wlen); if (ex_tag_first(sp, w)) goto err; } /* * Append any remaining arguments as file names. Files are recovery * files if -r specified. If the tag option or ex startup commands * loaded a file, then any file arguments are going to come after it. */ if (*argv != NULL) { if (sp->frp != NULL) { /* Cheat -- we know we have an extra argv slot. */ *--argv = strdup(sp->frp->name); if (*argv == NULL) { v_estr(gp->progname, errno, NULL); goto err; } } sp->argv = sp->cargv = argv; F_SET(sp, SC_ARGNOFREE); if (flagchk == 'r') F_SET(sp, SC_ARGRECOVER); } /* * If the ex startup commands and or/the tag option haven't already * created a file, create one. If no command-line files were given, * use a temporary file. */ if (sp->frp == NULL) { if (sp->argv == NULL) { if ((frp = file_add(sp, NULL)) == NULL) goto err; } else { if ((frp = file_add(sp, sp->argv[0])) == NULL) goto err; if (F_ISSET(sp, SC_ARGRECOVER)) F_SET(frp, FR_RECOVER); } if (file_init(sp, frp, NULL, 0)) goto err; if (EXCMD_RUNNING(gp)) { (void)ex_cmd(sp); if (F_ISSET(sp, SC_EXIT | SC_EXIT_FORCE)) { if (screen_end(sp)) goto err; goto done; } } } /* * Check to see if we need to wait for ex. If SC_SCR_EX is set, ex * was forced to initialize the screen during startup. We'd like to * wait for a single character from the user, but we can't because * we're not in raw mode. We can't switch to raw mode because the * vi initialization will switch to xterm's alternate screen, causing * us to lose the messages we're pausing to make sure the user read. * So, wait for a complete line. */ if (F_ISSET(sp, SC_SCR_EX)) { p = msg_cmsg(sp, CMSG_CONT_R, &len); (void)write(STDOUT_FILENO, p, len); for (;;) { if (v_event_get(sp, &ev, 0, 0)) goto err; if (ev.e_event == E_INTERRUPT || (ev.e_event == E_CHARACTER && (ev.e_value == K_CR || ev.e_value == K_NL))) break; (void)gp->scr_bell(sp); } } /* Switch into the right editor, regardless. */ F_CLR(sp, SC_EX | SC_VI); F_SET(sp, LF_ISSET(SC_EX | SC_VI) | SC_STATUS_CNT); /* * Main edit loop. Vi handles split screens itself, we only return * here when switching editor modes or restarting the screen. */ while (sp != NULL) if (F_ISSET(sp, SC_EX) ? ex(&sp) : vi(&sp)) goto err; done: rval = 0; if (0) err: rval = 1; /* Clean out the global structure. */ v_end(gp); return (rval); }
/** * Walk directory tree and call given callback function to process each file/directory. * * @param start_dir path to the directory to walk recursively * @param data the options specifying how to walk the directory tree * @return 0 on success, -1 on error */ static int dir_scan(file_t* start_dir, file_search_data* data) { dir_entry *dirs_stack = NULL; /* root of the dir_list */ dir_iterator* it; int level = 0; int max_depth = data->max_depth; int options = data->options; file_t file; if (max_depth < 0 || max_depth >= MAX_DIRS_DEPTH) { max_depth = MAX_DIRS_DEPTH - 1; } /* skip the directory if max_depth == 0 */ if (!max_depth) return 0; if (!FILE_ISDIR(start_dir)) { errno = ENOTDIR; return -1; } /* check if we should descend into the root directory */ if ((options & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS)) == 0) { if (!data->call_back(start_dir, data->call_back_data)) return 0; } /* allocate array of counters of directory elements */ it = (dir_iterator*)malloc((MAX_DIRS_DEPTH + 1) * sizeof(dir_iterator)); if (!it) { return -1; } /* push dummy counter for the root element */ it[0].count = 1; it[0].dir_path = 0; memset(&file, 0, sizeof(file)); while (!(data->options & FIND_CANCEL)) { dir_entry **insert_at; char* dir_path; DIR *dp; struct dirent *de; /* climb down from the tree */ while (--it[level].count < 0) { /* do not need this dir_path anymore */ free(it[level].dir_path); if (--level < 0) { /* walked the whole tree */ assert(!dirs_stack); free(it); return 0; } } assert(level >= 0 && it[level].count >= 0); /* take a filename from dirs_stack and construct the next path */ if (level) { assert(dirs_stack != NULL); dir_path = make_path(it[level].dir_path, dirs_stack->filename); dir_entry_drop_head(&dirs_stack); } else { /* the first cycle: start from a root directory */ dir_path = rsh_strdup(start_dir->path); } if (!dir_path) continue; /* fill the next level of directories */ level++; assert(level < MAX_DIRS_DEPTH); it[level].count = 0; it[level].dir_path = dir_path; if ((options & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS)) == FIND_WALK_DEPTH_FIRST) { int res; file_init(&file, dir_path, 1); res = file_stat2(&file, USE_LSTAT); /* check if we should skip the directory */ if (res < 0 || !data->call_back(&file, data->call_back_data)) { if (res < 0 && (options & FIND_LOG_ERRORS)) { data->errors_count++; } file_cleanup(&file); continue; } } file_cleanup(&file); /* step into directory */ dp = opendir(dir_path); if (!dp) continue; insert_at = &dirs_stack; while ((de = readdir(dp)) != NULL) { int res; /* skip the "." and ".." directories */ if (IS_CURRENT_OR_PARENT_DIR(de->d_name)) continue; file.mode = 0; file.path = make_path(dir_path, de->d_name); if (!file.path) continue; res = file_stat2(&file, USE_LSTAT); if (res >= 0) { /* process the file or directory */ if (FILE_ISDIR(&file) && (options & (FIND_WALK_DEPTH_FIRST | FIND_SKIP_DIRS))) { res = ((options & FIND_FOLLOW_SYMLINKS) || !FILE_ISLNK(&file)); } else if (FILE_ISREG(&file)) { /* handle file by callback function */ res = data->call_back(&file, data->call_back_data); } /* check if file is a directory and we need to walk it, */ /* but don't go deeper than max_depth */ if (FILE_ISDIR(&file) && res && level < max_depth && ((options & FIND_FOLLOW_SYMLINKS) || !FILE_ISLNK(&file))) { /* add the directory name to the dirs_stack */ if (dir_entry_insert(insert_at, de->d_name, file.mode)) { /* the directory name was successfully inserted */ insert_at = &((*insert_at)->next); it[level].count++; } } } else if (options & FIND_LOG_ERRORS) { /* report error only if FIND_LOG_ERRORS option is set */ log_file_error(file.path); data->errors_count++; } file_cleanup(&file); } closedir(dp); } while (dirs_stack) { dir_entry_drop_head(&dirs_stack); } while (level) { free(it[level--].dir_path); } free(it); assert(file.path == 0); return 0; }
int main(int argc, char *argv[]) { void *buf; _xcc_status cc; bool client = false; unsigned short count_written; unsigned short count_xferred; int ferr; short filenum; int inx; int loop = 10; char my_name[BUFSIZ]; bool nowait = false; char recv_buffer[BUFSIZ]; RI_Type ri; char send_buffer[BUFSIZ]; int send_len; SB_Tag_Type tag; int timeout = -1; short tfilenum; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-nowait", TA_Bool, TA_NOMAX, &nowait }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); util_gethostname(my_name, (int) sizeof(my_name)); if (client) { ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, nowait ? (short) 1 : (short) 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); send_len = (int) strlen(send_buffer) + 1; // cast cc = XWRITEX(filenum, send_buffer, (ushort) send_len, &count_written, 0); if (nowait) { TEST_CHK_CCEQ(cc); tfilenum = filenum; cc = XAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); assert(count_xferred == send_len); } else { TEST_CHK_CCEQ(cc); assert(count_written == send_len); } printf("%s\n", send_buffer); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 0, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, NULL, 0); TEST_CHK_CCEQ(cc); getri(&ri); assert(ri.io_type == XZSYS_VAL_RCV_IOTYPE_WRITE); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); cc = XREPLYX(NULL, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); assert(count_written == 0); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
static void conv(FILE *fp) /* FILE *fp; / * next input file */ { int ch; int c; /* * * Reads a troff output file and echoes most everything to *fp_out. Tracks a few * things, like the current font, so the state can be restored at the start of * each section. * */ file_init(); /* get ready for the next file */ while ( (ch = getc(fp)) != EOF ) { if ( ch != 'p' ) put_char(ch, fp_out); switch ( ch ) { case 'w': /* ignore these */ case ' ': case '\n': case 0: break; case '0': /* two digits and a character */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ( ! isdigit(c = getc(fp)) ) error(FATAL, "digit missing"); put_char(c, fp_out); /* fall through */ case 'c': /* ASCII character */ put_char(getc(fp), fp_out); break; case 'h': /* relative horizontal */ case 'H': /* absolute horizontal */ case 'v': /* relative vertical */ case 'V': /* and absolute vertical motion */ get_int(fp); break; case 'C': /* special character */ put_char(getc(fp), fp_out); put_char(getc(fp), fp_out); break; case 'D': /* drawing command */ case 't': /* text string */ case 'n': /* end of line */ case '#': /* comment */ do put_char(c = getc(fp), fp_out); while ( c != '\n' && c != EOF ); break; case 'x': /* device control */ devcntrl(fp); break; case 'p': /* new page */ new_page(); put_char(ch, fp_out); get_int(fp); break; case 's': /* point size */ size = get_int(fp); break; case 'f': /* font */ font = get_int(fp); break; default: /* something's wrong */ error(FATAL, "unknown input character 0%o %c", ch, ch); break; } /* End switch */ } /* End while */ if ( fp_out != stdout && do_report == ON ) fprintf(stdout, "%s\n", filename); } /* End of conv */
void SelectFile::callSWWYL() { QString inFile; QString inFile_2d; QString outPath; QDir dir(root_path+"/yubao/wenyanliu/3d_pic/"); QFileInfoList list; QFile file_init("initial.txt"); QTextStream fileOut(&file_init); inFile = ui->lineEdit->text(); outPath = ui->lineEdit_3->text(); QFileInfo fi(inFile); if(inFile.isEmpty() || outPath.isEmpty()){ QMessageBox::warning(0,"Warning",QStringLiteral("请选择输入文件和输出路径"),QMessageBox::Yes);//查看路径 }else { file_date = fi.fileName().mid(12,8); qDebug() << file_date << "1111111"; // return; //载入loading…动画 loadMovie->start(); ui->label_5->show(); // 清空原文件,复制用户选择的文件到程序运行目录,并重命名 // QFile::remove(root_path+"/yubao/wenyanliu/ocean_his_4750.nc"); list = dir.entryInfoList(); for(int i=0; i<list.size(); i++) { // QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); QFile::remove(list.at(i).filePath()); } // dir = QDir("C:/pic/SWWYL_3d"); // list = dir.entryInfoList(); // for(int i=0; i<list.size(); i++) // { //// QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); // QFile::remove(list.at(i).filePath()); // } // dir = QDir("C:/pic/SWWYL_2d"); // list = dir.entryInfoList(); // for(int i=0; i<list.size(); i++) // { //// QMessageBox::warning(0,"PATH",list.at(i).filePath(),QMessageBox::Yes); // QFile::remove(list.at(i).filePath()); // } copyFileToPath(inFile, root_path+"/yubao/wenyanliu/",true); inFile_2d = fi.absolutePath()+"/2d/ecs_new_"+file_date+".nc"; qDebug() << inFile_2d; copyFileToPath(inFile_2d, root_path+"/yubao/wenyanliu/",true); //m_fsw->removePaths(m_fsw->directories()); m_outPath = outPath; m_fsw->addPath( root_path+"/yubao/wenyanliu/3d_pic/"); // 写配置文件 initial1.txt 调用程序 qDebug() << root_path; QDir::setCurrent(root_path+"/yubao/wenyanliu/"); file_init.open(QIODevice::WriteOnly); fileOut << file_date << "\n"; file_init.close(); QProcess::startDetached("swwyl.exe"); // QProcess::execute("swwyl.exe"); // 还原系统路径 QDir::setCurrent(root_path); } }
static int diversion_remove(const char *const *argv) { const char *filename = argv[0]; struct fsys_namenode *namenode; struct fsys_diversion *contest, *altname; struct file file_from, file_to; struct pkgset *pkgset; opt_rename_setup(); if (!filename || argv[1]) badusage(_("--%s needs a single argument"), cipaction->olong); diversion_check_filename(filename); namenode = fsys_hash_find_node(filename, FHFF_NONE); if (namenode == NULL || namenode->divert == NULL || namenode->divert->useinstead == NULL) { if (opt_verbose > 0) printf(_("No diversion '%s', none removed.\n"), diversion_current(filename)); return 0; } if (opt_pkgname == NULL) pkgset = NULL; else pkgset = pkg_hash_find_set(opt_pkgname); contest = namenode->divert; altname = contest->useinstead->divert; if (opt_divertto != NULL && strcmp(opt_divertto, contest->useinstead->name) != 0) ohshit(_("mismatch on divert-to\n" " when removing '%s'\n" " found '%s'"), diversion_current(filename), diversion_describe(contest)); if (!opt_pkgname_match_any && pkgset != contest->pkgset) ohshit(_("mismatch on package\n" " when removing '%s'\n" " found '%s'"), diversion_current(filename), diversion_describe(contest)); /* Ignore removal request if the diverted file is still owned * by another package in the same set. */ if (diversion_is_shared(pkgset, namenode)) { if (opt_verbose > 0) printf(_("Ignoring request to remove shared diversion '%s'.\n"), diversion_describe(contest)); return 0; } if (opt_verbose > 0) printf(_("Removing '%s'\n"), diversion_describe(contest)); file_init(&file_from, altname->camefrom->name); file_init(&file_to, contest->useinstead->name); /* Remove entries from database. */ contest->useinstead->divert = NULL; altname->camefrom->divert = NULL; if (opt_rename) opt_rename = check_rename(&file_to, &file_from); if (opt_rename && !opt_test) file_rename(&file_to, &file_from); if (!opt_test) divertdb_write(); return 0; }
static int diversion_add(const char *const *argv) { const char *filename = argv[0]; struct file file_from, file_to; struct fsys_diversion *contest, *altname; struct fsys_namenode *fnn_from, *fnn_to; struct pkgset *pkgset; opt_pkgname_match_any = false; opt_rename_setup(); /* Handle filename. */ if (!filename || argv[1]) badusage(_("--%s needs a single argument"), cipaction->olong); diversion_check_filename(filename); file_init(&file_from, filename); file_stat(&file_from); if (file_from.stat_state == FILE_STAT_VALID && S_ISDIR(file_from.stat.st_mode)) badusage(_("cannot divert directories")); fnn_from = fsys_hash_find_node(filename, 0); /* Handle divertto. */ if (opt_divertto == NULL) opt_divertto = str_fmt("%s.distrib", filename); if (strcmp(filename, opt_divertto) == 0) badusage(_("cannot divert file '%s' to itself"), filename); file_init(&file_to, opt_divertto); fnn_to = fsys_hash_find_node(opt_divertto, 0); /* Handle package name. */ if (opt_pkgname == NULL) pkgset = NULL; else pkgset = pkg_hash_find_set(opt_pkgname); /* Check we are not stomping over an existing diversion. */ if (fnn_from->divert || fnn_to->divert) { if (fnn_to->divert && fnn_to->divert->camefrom && strcmp(fnn_to->divert->camefrom->name, filename) == 0 && fnn_from->divert && fnn_from->divert->useinstead && strcmp(fnn_from->divert->useinstead->name, opt_divertto) == 0 && fnn_from->divert->pkgset == pkgset) { if (opt_verbose > 0) printf(_("Leaving '%s'\n"), diversion_describe(fnn_from->divert)); return 0; } ohshit(_("'%s' clashes with '%s'"), diversion_current(filename), fnn_from->divert ? diversion_describe(fnn_from->divert) : diversion_describe(fnn_to->divert)); } /* Create new diversion. */ contest = nfmalloc(sizeof(*contest)); altname = nfmalloc(sizeof(*altname)); altname->camefrom = fnn_from; altname->camefrom->divert = contest; altname->useinstead = NULL; altname->pkgset = pkgset; contest->useinstead = fnn_to; contest->useinstead->divert = altname; contest->camefrom = NULL; contest->pkgset = pkgset; /* Update database and file system if needed. */ if (opt_verbose > 0) printf(_("Adding '%s'\n"), diversion_describe(contest)); if (opt_rename) opt_rename = check_rename(&file_from, &file_to); /* Check we are not renaming a file owned by the diverting pkgset. */ if (opt_rename && diversion_is_owned_by_self(pkgset, fnn_from)) { if (opt_verbose > 0) printf(_("Ignoring request to rename file '%s' " "owned by diverting package '%s'\n"), filename, pkgset->name); opt_rename = false; } if (opt_rename && diversion_is_essential(fnn_from)) warning(_("diverting file '%s' from an Essential package with " "rename is dangerous, use --no-rename"), filename); if (!opt_test) { divertdb_write(); if (opt_rename) file_rename(&file_from, &file_to); } return 0; }
int main(void) { FILE *primefile; char first_range_string[128], second_range_string[128]; char *endptr; unsigned char filecount; bool line_number_switch; u_long_64 file_linecount, *semiprimes = NULL, semiprimes_count = 0; u_long_64 first_range,second_range; unsigned int x; int perc = 0; welcome(); for(;;) { // first, lets clean up memset(first_range_string,'\0',128); memset(second_range_string,'\0',128); first_range=second_range=perc=0; line_number_switch=0; filecount=1; file_linecount=2; //! First Range printf("\n\nPlease enter the lowest range number: "); scanf("%s",&first_range_string); if(!strcasecmp("exit",first_range_string)) return 0; if(first_range_string[0] == '-') { negative_input(); /*if the input is negative, show the error message*/ continue; // you can see continue just like goto } first_range = strtoull(first_range_string,&endptr,0); if(*endptr == '.') /*if the user types a float number, show this message*/ decimal_input(first_range, first_range_string); if((*endptr) && *endptr != '.') { only_numbers(); continue; } //! Second Range printf("Please enter the highest range number: "); scanf("%s",&second_range_string); if(!strcasecmp("exit",second_range_string)) return(0); if(second_range_string[0] == '-') { negative_input(); /*if the input is negative, show the error message*/ continue; } second_range = strtoull(second_range_string,&endptr,0); if(*endptr == '.') decimal_input(second_range, second_range_string); /*if the user types a float number, show this message*/ if((*endptr) && *endptr != '.') { only_numbers(); continue; } //! Check Ranges if(first_range>=second_range) /*if the user types a bad range, show error message*/ { bad_ranges(); continue; } //! End error check printf("\n"); primefile = file_init(primefile); semiprimes = semiprimegen(first_range, second_range, &semiprimes_count); #ifdef PROGRESS printf("\nWriting to file...\n"); #ifdef WIN32 fflush(stdout); #else fpurge(stoud); #endif #endif // prints semiprimes found for(x=0; x<semiprimes_count; x++) { // printf(VAL_FORMAT "\t", *(semiprimes + x)); if(line_number_switch==0) // first line { fprintf(primefile,"1."); line_number_switch=true; } fprintf(primefile,"\t" VAL_FORMAT , *(semiprimes + x)); // print the number to the text file if(filecount==10) // it will insert a new line in the text file, change value if desired { fprintf(primefile,"\n" VAL_FORMAT ".",file_linecount); filecount=0; // reset file_linecount++; // number of lines written } filecount++; // number of printed primes #ifdef PROGRESS if( (perc+1) <= (int)(100.0 * x / semiprimes_count)) { perc = (int)(100.0 * x / semiprimes_count); progress(false, perc); } #endif } #ifdef PROGRESS progress(false, 100); printf("\n"); #ifdef WIN32 fflush(stdout); #else fpurge(stoud); #endif #endif results(primefile, first_range, second_range, semiprimes_count); //! After Results Given // unload free(semiprimes); printf("\nCheck the \"semiprimes.txt\" file,\nGenerated in the same Directory this Program is In.\n"); } //! End for return 0; }
/* allocate and fill the file_search_data */ file_search_data* create_file_search_data(rsh_tchar** paths, size_t count, int max_depth) { size_t i; file_search_data* data = (file_search_data*)rsh_malloc(sizeof(file_search_data)); memset(data, 0, sizeof(file_search_data)); rsh_blocks_vector_init(&data->root_files); data->max_depth = max_depth; #ifdef _WIN32 /* expand wildcards and fill the root_files */ for (i = 0; i < count; i++) { int added = 0; size_t length, index; wchar_t* path = paths[i]; wchar_t* p = wcschr(path, L'\0') - 1; /* strip trailing '\','/' symbols (if not preceded by ':') */ for (; p > path && IS_PATH_SEPARATOR_W(*p) && p[-1] != L':'; p--) *p = 0; /* Expand a wildcard in the current file path and store results into data->root_files. * If a wildcard is not found then just the file path is stored. * NB, only wildcards in the last filename of the path are expanded. */ length = p - path + 1; index = wcscspn(path, L"*?"); if (index < length && wcscspn(path + index, L"/\\") >= (length - index)) { /* a wildcard is found without a directory separator after it */ wchar_t* parent; WIN32_FIND_DATAW d; HANDLE handle; /* find a directory separator before the file name */ for (; index > 0 && !IS_PATH_SEPARATOR(path[index]); index--); parent = (IS_PATH_SEPARATOR(path[index]) ? path : 0); handle = FindFirstFileW(path, &d); if (INVALID_HANDLE_VALUE != handle) { do { file_t file; int failed; if (IS_CURRENT_OR_PARENT_DIRW(d.cFileName)) continue; memset(&file, 0, sizeof(file)); file.wpath = make_pathw(parent, index + 1, d.cFileName); if (!file.wpath) continue; /* skip directories if not in recursive mode */ if (data->max_depth == 0 && (d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue; /* convert file name */ file.path = wchar_to_cstr(file.wpath, WIN_DEFAULT_ENCODING, &failed); if (!failed) { failed = (file_statw(&file) < 0); } /* quietly skip unconvertible file names */ if (!file.path || failed) { if (failed) { data->errors_count++; } free(file.path); free(file.wpath); continue; } /* fill the file information */ file.mode |= FILE_IFROOT; add_root_file(data, &file); added++; } while (FindNextFileW(handle, &d)); FindClose(handle); } else { /* report error on the specified wildcard */ char * cpath = wchar_to_cstr(path, WIN_DEFAULT_ENCODING, NULL); set_errno_from_last_file_error(); log_file_error(cpath); free(cpath); data->errors_count++; } } else { int failed; file_t file; memset(&file, 0, sizeof(file)); /* if filepath is a dash string "-" */ if ((path[0] == L'-' && path[1] == L'\0')) { file.mode = FILE_IFSTDIN; file.path = rsh_strdup("(stdin)"); } else { file.path = wchar_to_cstr(path, WIN_DEFAULT_ENCODING, &failed); if (failed) { log_error(_("Can't convert the path to local encoding: %s\n"), file.path); free(file.path); data->errors_count++; continue; } file.wpath = path; if (file_statw(&file) < 0) { log_file_error(file.path); free(file.path); data->errors_count++; continue; } } /* mark the file as obtained from the command line */ file.mode |= FILE_IFROOT; file.wpath = rsh_wcsdup(path); add_root_file(data, &file); } } /* for */ #else /* copy file paths */ for (i = 0; i < count; i++) { file_t file; file_init(&file, paths[i], 0); if (IS_DASH_STR(file.path)) { file.mode = FILE_IFSTDIN; } else if (file_stat2(&file, USE_LSTAT) < 0) { log_file_error(file.path); file_cleanup(&file); data->errors_count++; continue; } file.mode |= FILE_IFROOT; add_root_file(data, &file); } #endif return data; }
/** Initialize the FreeWPC program. */ __noreturn__ void freewpc_init (void) { extern __common__ void system_reset (void); /* Initialize the platform specifics first */ VOIDCALL (platform_init); /* Reset the blanking and watchdog circuitry. * Eventually, the watchdog will be tickled every 1ms * by the IRQ; until interrupts are enabled, we will * have to do this periodically ourselves. */ pinio_watchdog_reset (); /* Set init complete flag to false. When everything is * ready, we'll change this to a 1. */ sys_init_complete = 0; periodic_ok = 0; sys_init_pending_tasks = 0; /* Initialize all of the other kernel subsystems, * starting with the hardware-centric ones and moving on * to software features. */ /* Initialize the real-time scheduler. The periodic functions are scheduled at compile-time using the 'gensched' utility. */ VOIDCALL (tick_init); /* Initialize the hardware. * After each init call, tickle the watchdog (IRQ isn't enabled yet) * to prevent it from expiring and resetting the CPU. * We don't use a callset here because there are some ordering * dependencies -- some modules must be initialized before others -- * and gencallset doesn't allow us to express those conditions. */ #ifdef DEBUGGER db_init (); bpt_init (); pinio_watchdog_reset (); #endif #ifdef CONFIG_AC ac_init (); pinio_watchdog_reset (); #endif sol_init (); pinio_watchdog_reset (); #ifdef CONFIG_GI gi_init (); pinio_watchdog_reset (); #endif display_init (); pinio_watchdog_reset (); switch_init (); pinio_watchdog_reset (); flipper_init (); pinio_watchdog_reset (); lamp_init (); pinio_watchdog_reset (); device_init (); pinio_watchdog_reset (); free_timer_init (); pinio_watchdog_reset (); sound_init (); pinio_watchdog_reset (); #if (MACHINE_PIC == 1) pic_init (); pinio_watchdog_reset (); #endif /* task_init is somewhat special in that it transforms the system * from a single task into a multitasking one. After this, tasks * can be spawned if need be. A task is created for the current * thread of execution, too. */ task_init (); pinio_watchdog_reset (); #ifdef CONFIG_NATIVE /* Notify the simulator when the core OS is up and running. */ sim_init (); #endif /* Initialize the sound board early in a background * thread, since it involves polling for data back from it, * which may take unknown (or even infinite) time. */ sys_init_pending_tasks++; task_create_gid (GID_SOUND_INIT, sound_board_init); /* Enable interrupts (IRQs and FIRQs). Do this as soon as possible, * but not before all of the hardware modules are done. */ enable_interrupts (); /* Check all adjustments and make sure that their checksums are valid. If problems are found, those adjustments will be made sane again. */ file_init (); /* Initialize everything else. Some of these are given explicitly to force a particular order, since callsets do not guarantee the order of invocation. For most things the order doesn't matter. */ deff_init (); leff_init (); test_init (); adj_init (); log_init (); callset_invoke (init); /* Enable periodic processing. */ periodic_ok = 1; task_sleep (TIME_16MS); /* The system is initialized from a hardware perspective. * Now, perform additional final initializations. */ system_reset (); /* The system can run itself now, this task is done! */ task_exit (); }
int main(int argc, char *argv[]) { _xcc_status cc; bool client = false; unsigned short count_read; int count_read_b; unsigned short count_written; TCPU_DECL (cpu); int ferr; short filenum; int inx; int loop = 10; TPT_DECL (mphandle); char *mphandlec = (char *) &mphandle; TPT_DECL_INT (mphandlei); int nid; char nodename[20]; short nodename_length; int nodenumber; int pid; TPIN_DECL (pin); char procname[40]; short procname_length; SB_Int64_Type sequence_number; const char *sname = "$srv"; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-sname", TA_Str, TA_NOMAX, &sname }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); ferr = msg_mon_get_my_process_name(my_name, BUFSIZ); util_check("msg_mon_get_my_process_name", ferr); ferr = msg_mon_get_process_info(my_name, &nid, &pid); TEST_CHK_FEOK(ferr); ferr = XPROCESSHANDLE_GETMINE_(TPT_REF(mphandle)); util_check("XPROCESSHANDLE_GETMINE_", ferr); TPT_COPY_INT(mphandlei, mphandle); assert((mphandlei[0] & 0xf0) == 0x20); // named assert(strncmp(my_name, &mphandlec[4], 32) == 0); printf("phandle=%x.%x.%x.%x.%x, pname=%s\n", mphandlei[0], mphandlei[1], mphandlei[2], mphandlei[3], mphandlei[4], my_name); ferr = XPROCESSHANDLE_DECOMPOSE_(TPT_REF(mphandle), &cpu, &pin, &nodenumber, nodename, sizeof(nodename), &nodename_length, procname, sizeof(procname), &procname_length, &sequence_number); assert(cpu == nid); assert(pin == pid); assert(nodenumber == 0); assert(nodename_length == 4); nodename[nodename_length] = 0; assert(strcmp(nodename, "\\NSK") == 0); procname[procname_length] = 0; assert(strcmp(procname, my_name) == 0); #ifdef SQ_PHANDLE_VERIFIER assert(sequence_number != 0); #else assert(sequence_number == 0); #endif if (client) { ferr = XFILE_OPEN_((char *) sname, 4, &filenum, 0, 0, 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); if ((inx & 1) == 0) cc = XWRITEREADX2(filenum, send_buffer, (unsigned short) (strlen(send_buffer) + 1), // cast recv_buffer, BUFSIZ, &count_read, 0); else cc = BWRITEREADX2(filenum, send_buffer, (unsigned short) (strlen(send_buffer) + 1), // cast recv_buffer, BUFSIZ, &count_read_b, 0); TEST_CHK_CCEQ(cc); printf("%s\n", recv_buffer); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 0, 1, 1, // no sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (unsigned short) (strlen(recv_buffer) + 1); // cast cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
int main(int argc, char *argv[]) { _xcc_status cc; bool client = false; unsigned short count_read; unsigned short count_written; int ferr; short filenum; short filenuma[2]; int inx; int loop = 10; char my_name[BUFSIZ]; char recv_buffer[BUFSIZ]; RI_Type ri; char send_buffer[BUFSIZ]; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); util_gethostname(my_name, (int) sizeof(my_name)); if (client) { ferr = XFILE_OPEN_((char *) "$srv", 4, &filenum, 0, 0, 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); short filenumx; ferr = XFILE_OPEN_((char *) "$srv", 4, &filenumx, 0, 0, 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); cc = XWRITEREADX(filenum, send_buffer, (short) (strlen(send_buffer) + 1), BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); printf("%s\n", send_buffer); } } else { ferr = XFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 0, 1, 0, // sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); // pick up opens for (inx = 0; inx < 2; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCNE(cc); getri(&ri); assert(recv_buffer[0] == XZSYS_VAL_SMSG_OPEN); assert(ri.io_type == 0); filenuma[inx] = ri.file_number; cc = XREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } for (inx = 0; inx < loop; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCEQ(cc); getri(&ri); assert(ri.io_type == XZSYS_VAL_RCV_IOTYPE_WRITEREAD); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (short) (strlen(recv_buffer) + 1); cc = XREPLYX(recv_buffer, count_read, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } // pick up close for (inx = 0; inx < 2; inx++) { cc = XREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); TEST_CHK_CCNE(cc); getri(&ri); assert(recv_buffer[0] == XZSYS_VAL_SMSG_CLOSE); assert(ri.io_type == 0); if (ri.file_number == filenuma[0]) filenuma[0] = -1; else if (ri.file_number == filenuma[1]) filenuma[1] = -1; else assert(false); // needs to be matching cc = XREPLYX(recv_buffer, 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
///////////////////////////////////////////////////////////////////////////// // Main-Funktion ///////////////////////////////////////////////////////////////////////////// int main(int argc, const char *argv[]) { // Initializations // // first some basic hardware infrastructure timer_init(); // Timer Interrupt initialisieren led_init(); provider_init(); // needs to be in the beginning, as other // modules like serial register here term_init(); // does not need endpoint/provider yet // but can take up to a buffer of text #ifdef __AVR__ stdout = &term_stdout; // redirect stdout #else device_setup(argc, argv); #endif // server communication uarthw_init(); // first hardware provider_t *serial = serial_init(); // then logic layer // now prepare for terminal etc // (note: in the future the assign parameter could be used // to distinguish different UARTs for example) void *epdata = serial->prov_assign(NAMEINFO_UNUSED_DRIVE, NULL); term_endpoint.provider = serial; term_endpoint.provdata = epdata; // and set as default provider_set_default(serial, epdata); // debug output via "terminal" term_set_endpoint(&term_endpoint); // init file handling (active open calls) file_init(); // buffer structures buffer_init(); // direct buffer handling direct_init(); // relfile handling relfile_init(); // init main channel handling channel_init(); // before we init any busses, we init the runtime config code // note it gets the provider to register a listener for X command line params rtconfig_init(&term_endpoint); // bus init // first the general bus (with bus counter) bus_init(); // this call initializes the device-specific hardware // e.g. IEEE488 and IEC busses on xs1541, plus SD card on petSD and so on // it also handles the interrupt initialization if necessary device_init(); #ifdef HAS_EEPROM // read bus-independent settings from non volatile memory nv_restore_common_config(); #endif // enable interrupts enable_interrupts(); // sync with the server serial_sync(); // pull in command line config options from server // also send directory charset rtconfig_pullconfig(argc, argv); #ifdef USE_FAT // register fat provider provider_register("FAT", &fat_provider); //provider_assign(0, "FAT", "/"); // might be overwritten when fetching X-commands //provider_assign(1, "FAT", "/"); // from the server, but useful for standalone-mode #endif // show our version... ListVersion(); // ... and some system info term_printf((" %u Bytes free"), BytesFree()); term_printf((", %d kHz"), FreqKHz()); #ifdef __AVR__ fuse_info(); #endif term_putcrlf(); term_putcrlf(); while (1) // Mainloop-Begin { // keep data flowing on the serial line main_delay(); if (!is_locked) device_loop(); // send out log messages term_flush(); } }
int main(int argc, char *argv[]) { bool bidir = false; bool bm = false; void *buf; double busy; _xcc_status cc; int count_read; int count_written; int count_xferred; int dsize = 1024; int ferr; short filenum[MAX_SERVERS]; short filenumr; int inx; int loop = 10; int max; int maxsp = 1; bool mq = false; bool nocopy = false; bool nowaitc = false; bool nowaits = false; int pinx; struct rusage r_start; struct rusage r_stop; char *recv_buffer_ptr; RI_Type ri; short sender_len; int sys_msg; struct timeval t_elapsed_data; struct timeval t_elapsed_open; struct timeval t_elapsed_total; struct timeval t_start_data; struct timeval t_start_total; struct timeval t_stop; SB_Tag_Type tag; short tfilenum; int timeout = -1; bool verbose = false; TAD zargs[] = { { "-bidir", TA_Bool, TA_NOMAX, &bidir }, { "-bm", TA_Bool, TA_NOMAX, &bm }, { "-client", TA_Bool, TA_NOMAX, &client }, { "-dsize", TA_Int, MAX_DBUF, &dsize }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-maxcp", TA_Int, MAX_CLIENTS, &maxcp }, { "-maxsp", TA_Int, MAX_SERVERS, &maxsp }, { "-mq", TA_Bool, TA_NOMAX, &mq }, { "-nocopy", TA_Bool, TA_NOMAX, &nocopy }, { "-nowaitc", TA_Bool, TA_NOMAX, &nowaitc }, { "-nowaits", TA_Bool, TA_NOMAX, &nowaits }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; for (inx = 0; inx < MAX_CLIENTS; inx++) account[inx] = 0; signal(SIGUSR2, printaccount); ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); if (maxcp < 0) maxcp = 1; if (maxsp < 0) maxsp = 1; util_test_start(client); ferr = file_mon_process_startup(!client); // system messages? TEST_CHK_FEOK(ferr); if (nocopy) { ferr = file_buf_register(buf_alloc, buf_free); TEST_CHK_FEOK(ferr); } ferr = msg_mon_get_my_process_name(my_name, BUFSIZ); TEST_CHK_FEOK(ferr); // process-wait for clients/servers/shell ferr = msfs_util_wait_process_count(MS_ProcessType_Generic, maxcp + maxsp + 1, NULL, verbose); if (client) sleep(1); util_time_timer_start(&t_start_total); if (client) { inx = atoi(&my_name[4]); printf("dsize=%d, loop=%d\n", dsize, loop); for (pinx = 0; pinx < maxsp; pinx++) { sprintf(serv, "$srv%d", pinx); ferr = BFILE_OPEN_(serv, (short) strlen(serv), &filenum[pinx], 0, 0, nowaitc ? (short) 1 : (short) 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); } util_time_timer_start(&t_start_data); util_cpu_timer_start(&r_start); util_time_elapsed(&t_start_total, &t_start_data, &t_elapsed_open); max = loop; for (inx = 0; inx < max; inx++) { for (pinx = 0; pinx < maxsp; pinx++) { if (pinx == 0) { if (verbose) printf("%s-count=%d\n", my_name, inx); else if (mq && ((inx % 1000) == 0)) printf("%s-count=%d\n", my_name, inx); } cc = BWRITEREADX(filenum[pinx], send_buffer, (int) dsize, // cast bidir ? dsize : 0, &count_read, 0); } for (pinx = 0; pinx < maxsp; pinx++) { if (nowaitc) { TEST_CHK_CCEQ(cc); tfilenum = filenum[pinx]; cc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); TEST_CHK_CCEQ(cc); } } } } else { ferr = BFILE_OPEN_((char *) "$RECEIVE", 8, &filenumr, 0, 0, nowaits ? (short) 1 : (short) 0, // nowait 1, 0, // sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); util_time_timer_start(&t_start_data); util_cpu_timer_start(&r_start); max = maxcp * loop; for (inx = 0; inx < max; inx++) { if (nocopy) { cc = file_buf_readupdatex(filenumr, &recv_buffer_ptr, &count_read, 0); buf_free(recv_buffer_ptr); } else cc = BREADUPDATEX(filenumr, recv_buffer, (int) dsize, // cast &count_read, 0); if (nowaits) { tfilenum = -1; cc = BAWAITIOX(&tfilenum, &buf, &count_xferred, &tag, timeout, NULL); // don't check cc - could be sys msg sys_msg = _xstatus_ne(cc); } else sys_msg = _xstatus_ne(cc); if (sys_msg) inx--; if (!sys_msg) { getri(&ri); ferr = XPROCESSHANDLE_DECOMPOSE_(TPT_REF(ri.sender), NULL, // cpu NULL, // pin NULL, // nodenumber NULL, // nodename 0, // nodename NULL, // nodename_length sender, sizeof(sender), &sender_len, NULL); // sequence_number TEST_CHK_FEOK(ferr); sender[sender_len] = 0; if (verbose) printf("sender=%s\n", sender); char *p = &sender[4]; // past $cli int sender_inx = atoi(p); account[sender_inx]++; } cc = BREPLYX(recv_buffer, bidir ? dsize : 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); } } util_cpu_timer_stop(&r_stop); util_time_timer_stop(&t_stop); util_time_elapsed(&t_start_total, &t_stop, &t_elapsed_total); util_time_elapsed(&t_start_data, &t_stop, &t_elapsed_data); util_cpu_timer_busy(&r_start, &r_stop, &t_elapsed_data, &busy); if (client) { if (!bm) { print_elapsed("", &t_elapsed_total); print_elapsed(" (data)", &t_elapsed_data); print_elapsed(" (open)", &t_elapsed_open); } print_rate(bm, "", bidir ? 2 * loop : loop, dsize, &t_elapsed_data, busy); } else print_server_busy(bm, "", busy); if (client) { for (pinx = 0; pinx < maxsp; pinx++) { ferr = BFILE_CLOSE_(filenum[pinx], 0); TEST_CHK_FEOK(ferr); } } else { ferr = BFILE_CLOSE_(filenumr, 0); TEST_CHK_FEOK(ferr); ferr = file_mon_process_close(); TEST_CHK_FEOK(ferr); } ferr = file_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); printaccount(0); return 0; }
int main_real(int argc, char * const* argv) { xmlerror *error = NULL; char *config_file = NULL, *command=NULL, *startup_file=NULL; int opt; char *cp; struct attr navit, conf; GList *list = NULL, *li; main_argc=argc; main_argv=argv; #ifdef HAVE_GLIB event_glib_init(); #else _g_slice_thread_init_nomessage(); #endif atom_init(); main_init(argv[0]); navit_nls_main_init(); debug_init(argv[0]); cp = getenv("NAVIT_LOGFILE"); if (cp) { debug_set_logfile(cp); } #ifdef HAVE_API_WIN32_CE else { debug_set_logfile("/Storage Card/navit.log"); } #endif file_init(); #ifndef USE_PLUGINS builtin_init(); #endif route_init(); navigation_init(); tracking_init(); search_init(); linguistics_init(); geom_init(); config_file=NULL; #ifdef HAVE_GETOPT_H opterr=0; //don't bomb out on errors. #endif /* _MSC_VER */ /* ingore iphone command line argument */ if (argc == 2 && !strcmp(argv[1],"-RegisterForSystemEvents")) argc=1; if (argc > 1) { /* Don't forget to update the manpage if you modify theses options */ while((opt = getopt(argc, argv, ":hvc:d:e:s:")) != -1) { switch(opt) { case 'h': print_usage(); exit(0); break; case 'v': printf("%s %s\n", "navit", version); exit(0); break; case 'c': printf("config file n is set to `%s'\n", optarg); config_file = optarg; break; case 'd': debug_set_global_level(atoi(optarg), 1); break; case 'e': command=optarg; break; case 's': startup_file=optarg; break; #ifdef HAVE_GETOPT_H case ':': fprintf(stderr, "navit: Error - Option `%c' needs a value\n", optopt); print_usage(); exit(2); break; case '?': fprintf(stderr, "navit: Error - No such option: `%c'\n", optopt); print_usage(); exit(3); #endif } } // use 1st cmd line option that is left for the config file if (optind < argc) config_file = argv[optind]; } // if config file is explicitely given only look for it, otherwise try std paths if (config_file) { list = g_list_append(list,g_strdup(config_file)); } else { list = g_list_append(list,g_strjoin(NULL,getenv("NAVIT_USER_DATADIR"), "/navit.xml" , NULL)); list = g_list_append(list,g_strdup("navit.xml.local")); list = g_list_append(list,g_strdup("navit.xml")); #ifdef HAVE_API_ANDROID // new preferred location (the new one should have priority over the legacy!) list = g_list_append(list,g_strdup("/sdcard/navit/navit.xml")); // legacy location, still supported list = g_list_append(list,g_strdup("/sdcard/navit.xml")); #endif list = g_list_append(list,g_strjoin(NULL,getenv("NAVIT_SHAREDIR"), "/navit.xml.local" , NULL)); list = g_list_append(list,g_strjoin(NULL,getenv("NAVIT_SHAREDIR"), "/navit.xml" , NULL)); #ifndef _WIN32 list = g_list_append(list,g_strdup("/etc/navit/navit.xml")); #endif } li = list; for (;;) { if (li == NULL) { // We have not found an existing config file from all possibilities dbg(0, "%s", _("No config file navit.xml, navit.xml.local found\n")); return 4; } // Try the next config file possibility from the list config_file = li->data; dbg(1,"trying %s\n",config_file); if (file_exists(config_file)) { break; } g_free(config_file); li = g_list_next(li); } dbg(0,"Loading %s\n",config_file); if (!config_load(config_file, &error)) { dbg(0, _("Error parsing config file '%s': %s\n"), config_file, error ? error->message : ""); } else { dbg(0, _("Using config file '%s'\n"), config_file); } while (li) { g_free(li->data); li = g_list_next(li); } g_list_free(list); if (! config_get_attr(config, attr_navit, &navit, NULL) && !config_empty_ok) { dbg(0, "%s", _("Internal initialization failed, exiting. Check previous error messages.\n")); exit(5); } conf.type=attr_config; conf.u.config=config; if (startup_file) { FILE *f=fopen(startup_file,"r"); if (f) { char buffer[4096]; while(fgets(buffer, sizeof(buffer), f)) { command_evaluate(&conf, buffer); } } } if (command) { command_evaluate(&conf, command); } event_main_loop_run(); /* TODO: Android actually has no event loop, so we can't free all allocated resources here. Have to find better place to * free all allocations on program exit. And don't forget to free all the stuff allocated in the code above. */ #ifndef HAVE_API_ANDROID linguistics_free(); debug_finished(); #endif return 0; }
int main(int argc,const char *argv[]) { /* shall I run as a daemon */ bool is_daemon = false; bool interactive = false; bool Fork = true; bool no_process_group = false; bool log_stdout = false; char *ports = NULL; char *profile_level = NULL; int opt; poptContext pc; bool print_build_options = False; enum { OPT_DAEMON = 1000, OPT_INTERACTIVE, OPT_FORK, OPT_NO_PROCESS_GROUP, OPT_LOG_STDOUT }; struct poptOption long_options[] = { POPT_AUTOHELP {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" }, {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"}, {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" }, {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" }, {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" }, {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" }, {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"}, {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"}, POPT_COMMON_SAMBA POPT_COMMON_DYNCONFIG POPT_TABLEEND }; struct smbd_parent_context *parent = NULL; TALLOC_CTX *frame; NTSTATUS status; uint64_t unique_id; struct tevent_context *ev_ctx; struct messaging_context *msg_ctx; /* * Do this before any other talloc operation */ talloc_enable_null_tracking(); frame = talloc_stackframe(); setup_logging(argv[0], DEBUG_DEFAULT_STDOUT); load_case_tables(); smbd_init_globals(); TimeInit(); #ifdef HAVE_SET_AUTH_PARAMETERS set_auth_parameters(argc,argv); #endif pc = poptGetContext("smbd", argc, argv, long_options, 0); while((opt = poptGetNextOpt(pc)) != -1) { switch (opt) { case OPT_DAEMON: is_daemon = true; break; case OPT_INTERACTIVE: interactive = true; break; case OPT_FORK: Fork = false; break; case OPT_NO_PROCESS_GROUP: no_process_group = true; break; case OPT_LOG_STDOUT: log_stdout = true; break; case 'b': print_build_options = True; break; default: d_fprintf(stderr, "\nInvalid option %s: %s\n\n", poptBadOption(pc, 0), poptStrerror(opt)); poptPrintUsage(pc, stderr, 0); exit(1); } } poptFreeContext(pc); if (interactive) { Fork = False; log_stdout = True; } if (log_stdout) { setup_logging(argv[0], DEBUG_STDOUT); } else { setup_logging(argv[0], DEBUG_FILE); } if (print_build_options) { build_options(True); /* Display output to screen as well as debug */ exit(0); } #ifdef HAVE_SETLUID /* needed for SecureWare on SCO */ setluid(0); #endif set_remote_machine_name("smbd", False); if (interactive && (DEBUGLEVEL >= 9)) { talloc_enable_leak_report(); } if (log_stdout && Fork) { DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n")); exit(1); } /* we want to re-seed early to prevent time delays causing client problems at a later date. (tridge) */ generate_random_buffer(NULL, 0); /* get initial effective uid and gid */ sec_init(); /* make absolutely sure we run as root - to handle cases where people are crazy enough to have it setuid */ gain_root_privilege(); gain_root_group_privilege(); fault_setup(); dump_core_setup("smbd", lp_logfile()); /* we are never interested in SIGPIPE */ BlockSignals(True,SIGPIPE); #if defined(SIGFPE) /* we are never interested in SIGFPE */ BlockSignals(True,SIGFPE); #endif #if defined(SIGUSR2) /* We are no longer interested in USR2 */ BlockSignals(True,SIGUSR2); #endif /* POSIX demands that signals are inherited. If the invoking process has * these signals masked, we will have problems, as we won't recieve them. */ BlockSignals(False, SIGHUP); BlockSignals(False, SIGUSR1); BlockSignals(False, SIGTERM); /* Ensure we leave no zombies until we * correctly set up child handling below. */ CatchChild(); /* we want total control over the permissions on created files, so set our umask to 0 */ umask(0); reopen_logs(); DEBUG(0,("smbd version %s started.\n", samba_version_string())); DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE)); DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n", (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid())); /* Output the build options to the debug log */ build_options(False); if (sizeof(uint16) < 2 || sizeof(uint32) < 4) { DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n")); exit(1); } if (!lp_load_initial_only(get_dyn_CONFIGFILE())) { DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE())); exit(1); } /* Init the security context and global current_user */ init_sec_ctx(); /* * Initialize the event context. The event context needs to be * initialized before the messaging context, cause the messaging * context holds an event context. * FIXME: This should be s3_tevent_context_init() */ ev_ctx = server_event_context(); if (ev_ctx == NULL) { exit(1); } /* * Init the messaging context * FIXME: This should only call messaging_init() */ msg_ctx = server_messaging_context(); if (msg_ctx == NULL) { exit(1); } /* * Reloading of the printers will not work here as we don't have a * server info and rpc services set up. It will be called later. */ if (!reload_services(NULL, -1, False)) { exit(1); } /* ...NOTE... Log files are working from this point! */ DEBUG(3,("loaded services\n")); init_structs(); #ifdef WITH_PROFILE if (!profile_setup(msg_ctx, False)) { DEBUG(0,("ERROR: failed to setup profiling\n")); return -1; } if (profile_level != NULL) { int pl = atoi(profile_level); struct server_id src; DEBUG(1, ("setting profiling level: %s\n",profile_level)); src.pid = getpid(); set_profile_level(pl, src); } #endif if (!is_daemon && !is_a_socket(0)) { if (!interactive) DEBUG(0,("standard input is not a socket, assuming -D option\n")); /* * Setting is_daemon here prevents us from eventually calling * the open_sockets_inetd() */ is_daemon = True; } if (is_daemon && !interactive) { DEBUG( 3, ( "Becoming a daemon.\n" ) ); become_daemon(Fork, no_process_group, log_stdout); } generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id)); set_my_unique_id(unique_id); #if HAVE_SETPGID /* * If we're interactive we want to set our own process group for * signal management. */ if (interactive && !no_process_group) setpgid( (pid_t)0, (pid_t)0); #endif if (!directory_exist(lp_lockdir())) mkdir(lp_lockdir(), 0755); if (is_daemon) pidfile_create("smbd"); status = reinit_after_fork(msg_ctx, ev_ctx, procid_self(), false); if (!NT_STATUS_IS_OK(status)) { DEBUG(0,("reinit_after_fork() failed\n")); exit(1); } smbd_server_conn->msg_ctx = msg_ctx; smbd_setup_sig_term_handler(); smbd_setup_sig_hup_handler(ev_ctx, msg_ctx); /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */ if (smbd_memcache() == NULL) { exit(1); } memcache_set_global(smbd_memcache()); /* Initialise the password backed before the global_sam_sid to ensure that we fetch from ldap before we make a domain sid up */ if(!initialize_password_db(false, ev_ctx)) exit(1); if (!secrets_init()) { DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n")); exit(1); } if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) { struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_context()); if (!open_schannel_session_store(NULL, lp_ctx)) { DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n")); exit(1); } TALLOC_FREE(lp_ctx); } if(!get_global_sam_sid()) { DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n")); exit(1); } if (!sessionid_init()) { exit(1); } if (!connections_init(True)) exit(1); if (!locking_init()) exit(1); if (!messaging_tdb_parent_init(ev_ctx)) { exit(1); } if (!notify_internal_parent_init(ev_ctx)) { exit(1); } if (!serverid_parent_init(ev_ctx)) { exit(1); } if (!W_ERROR_IS_OK(registry_init_full())) exit(1); /* Open the share_info.tdb here, so we don't have to open after the fork on every single connection. This is a small performance improvment and reduces the total number of system fds used. */ if (!share_info_db_init()) { DEBUG(0,("ERROR: failed to load share info db.\n")); exit(1); } status = init_system_info(); if (!NT_STATUS_IS_OK(status)) { DEBUG(1, ("ERROR: failed to setup system user info: %s.\n", nt_errstr(status))); return -1; } if (!init_guest_info()) { DEBUG(0,("ERROR: failed to setup guest info.\n")); return -1; } if (!file_init(smbd_server_conn)) { DEBUG(0, ("ERROR: file_init failed\n")); return -1; } /* This MUST be done before start_epmd() because otherwise * start_epmd() forks and races against dcesrv_ep_setup() to * call directory_create_or_exist() */ if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) { DEBUG(0, ("Failed to create pipe directory %s - %s\n", lp_ncalrpc_dir(), strerror(errno))); return -1; } if (is_daemon && !interactive) { if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) { start_epmd(ev_ctx, msg_ctx); } } if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) { exit(1); } /* only start other daemons if we are running as a daemon * -- bad things will happen if smbd is launched via inetd * and we fork a copy of ourselves here */ if (is_daemon && !interactive) { if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) { start_lsasd(ev_ctx, msg_ctx); } if (!_lp_disable_spoolss() && (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) { bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true); if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) { exit(1); } } } else if (!_lp_disable_spoolss() && (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) { if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) { exit(1); } } if (!is_daemon) { /* inetd mode */ TALLOC_FREE(frame); /* Started from inetd. fd 0 is the socket. */ /* We will abort gracefully when the client or remote system goes away */ smbd_server_conn->sock = dup(0); /* close our standard file descriptors */ if (!debug_get_output_is_stdout()) { close_low_fds(False); /* Don't close stderr */ } #ifdef HAVE_ATEXIT atexit(killkids); #endif /* Stop zombies */ smbd_setup_sig_chld_handler(ev_ctx); smbd_process(ev_ctx, smbd_server_conn); exit_server_cleanly(NULL); return(0); } parent = talloc_zero(ev_ctx, struct smbd_parent_context); if (!parent) { exit_server("talloc(struct smbd_parent_context) failed"); } parent->interactive = interactive; if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports)) exit_server("open_sockets_smbd() failed"); /* do a printer update now that all messaging has been set up, * before we allow clients to start connecting */ printing_subsystem_update(ev_ctx, msg_ctx, false); TALLOC_FREE(frame); /* make sure we always have a valid stackframe */ frame = talloc_stackframe(); smbd_parent_loop(ev_ctx, parent); exit_server_cleanly(NULL); TALLOC_FREE(frame); return(0); }
int main(int argc, char *argv[]) { _bcc_status bcc; bool client = false; int count_read; int count_written; int disable; int err; short error_reply; int ferr; short filenum; int inx; short lasterr; int loop = 10; int msgnum; bool open = false; short sender_len; xzsys_ddl_smsg_def *sys_msg = (xzsys_ddl_smsg_def *) recv_buffer; RI_Type ri; TAD zargs[] = { { "-client", TA_Bool, TA_NOMAX, &client }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); msfs_util_init_fs(&argc, &argv, file_debug_hook); arg_proc_args(zargs, false, argc, argv); util_test_start(true); ferr = msg_mon_process_startup(!client); // system messages TEST_CHK_FEOK(ferr); ferr = msg_mon_get_my_process_name(my_name, BUFSIZ); TEST_CHK_FEOK(ferr); ferr = msg_mon_get_process_info(NULL, &my_nid, &my_pid); TEST_CHK_FEOK(ferr); if (client) { printf("client name=%s, nid=%d, pid=%d\n", my_name, my_nid, my_pid); start_server(argc, argv); server_name_len = (short) strlen(server_name); ferr = BFILE_OPEN_((char *) server_name, server_name_len, &filenum, 0, 0, 0, 0, 0, 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { sprintf(send_buffer, "hello, greetings from %s, inx=%d", my_name, inx); disable = msg_test_assert_disable(); bcc = BWRITEREADX(filenum, send_buffer, (int) (strlen(send_buffer) + 1), // cast BUFSIZ, &count_read, 0); msg_test_assert_enable(disable); if (_bstatus_eq(bcc)) printf("%s\n", send_buffer); else { ferr = XFILE_GETINFO_(-1, &lasterr, NULL, 0, NULL, NULL, NULL); printf("WRITEREAD error=%d\n", lasterr); } kill(server_pid, SIGKILL); for (;;) { err = kill(server_pid, 0); if ((err == -1) && (errno == ESRCH)) break; usleep(10000); } start_server(argc, argv); } kill(server_pid, SIGKILL); for (;;) { err = kill(server_pid, 0); if ((err == -1) && (errno == ESRCH)) break; usleep(10000); } ferr = BFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } else { printf("server name=%s, nid=%d, pid=%d\n", my_name, my_nid, my_pid); ferr = BFILE_OPEN_((char *) "$RECEIVE", 8, &filenum, 0, 0, 0, 1, 0, // sys msg 0, 0, NULL); TEST_CHK_FEOK(ferr); for (inx = 0; inx < loop; inx++) { bcc = BREADUPDATEX(filenum, recv_buffer, BUFSIZ, &count_read, 0); getri(&ri); printri(&ri); sender_len = 0; sender_nid = -1; sender_pid = -1; disable = msg_test_assert_disable(); // errors are ok ferr = XPROCESSHANDLE_DECOMPOSE_(TPT_REF(ri.sender), &sender_nid, // cpu &sender_pid, // pin NULL, // nodenumber NULL, // nodename 0, // nodename NULL, // nodename_length sender, sizeof(sender), &sender_len, NULL); // sequence_number TEST_CHK_FEIGNORE(ferr); msg_test_assert_enable(disable); sender[sender_len] = 0; printf("sender=%s, nid=%d, pid=%d\n", sender, sender_nid, sender_pid); error_reply = XZFIL_ERR_OK; if (_bstatus_eq(bcc)) { if (open) { assert(sender_nid == open_sender_nid); assert(sender_pid == open_sender_pid); assert(strcmp(sender, open_sender) == 0); assert(ri.file_number == open_sender_file_number); strcat(recv_buffer, "- reply from "); strcat(recv_buffer, my_name); count_read = (int) (strlen(recv_buffer) + 1); // cast } else { printf("server not opened by client - returning WRONGID\n"); error_reply = XZFIL_ERR_WRONGID; } } else { msgnum = sys_msg->u_z_msg.z_msgnumber[0]; switch (msgnum) { case XZSYS_VAL_SMSG_OPEN: printf("msgnum=%d (open)\n", msgnum); assert(!open); TPT_COPY_INT(TPT_REF(open_sender_phandle), ri.sender); strcpy(open_sender, sender); open_sender_nid = sender_nid; open_sender_pid = sender_pid; open_sender_file_number = ri.file_number; open = true; break; case XZSYS_VAL_SMSG_CLOSE: printf("msgnum=%d (close)\n", msgnum); assert(open); open = false; break; case XZSYS_VAL_SMSG_SHUTDOWN: printf("msgnum=%d (shutdown)\n", msgnum); inx = loop; // exit break; default: printf("unexpected msgnum=%d\n", msgnum); abort(); } count_read = 0; inx--; } bcc = BREPLYX(recv_buffer, count_read, &count_written, 0, error_reply); TEST_CHK_BCCEQ(bcc); } ferr = XFILE_CLOSE_(filenum, 0); TEST_CHK_FEOK(ferr); } ferr = msg_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(true); printf("if there were no asserts, all is well\n"); return 0; }
/* Read the items in a Vorbis comment packet. For Ogg files, the file must * be located on a page start, for other files, the beginning of the comment * data (i.e., the vendor string length). Returns total size of the * comments, or 0 if there was a read error. */ long read_vorbis_tags(int fd, struct mp3entry *id3, long tag_remaining) { struct file file; char *buf = id3->id3v2buf; int32_t comment_count; int32_t len; long comment_size = 0; int buf_remaining = sizeof(id3->id3v2buf) + sizeof(id3->id3v1buf); int i; if (!file_init(&file, fd, id3->codectype, tag_remaining)) { return 0; } /* Skip vendor string */ if (!file_read_int32(&file, &len) || (file_read(&file, NULL, len) < 0)) { return 0; } if (!file_read_int32(&file, &comment_count)) { return 0; } comment_size += 4 + len + 4; for (i = 0; i < comment_count && file.packet_remaining > 0; i++) { char name[TAG_NAME_LENGTH]; int32_t read_len; if (!file_read_int32(&file, &len)) { return 0; } comment_size += 4 + len; read_len = file_read_string(&file, name, sizeof(name), '=', len); if (read_len < 0) { return 0; } len -= read_len; read_len = file_read_string(&file, id3->path, sizeof(id3->path), -1, len); if (read_len < 0) { return 0; } logf("Vorbis comment %d: %s=%s", i, name, id3->path); /* Is it an embedded cuesheet? */ if (!strcasecmp(name, "CUESHEET")) { id3->has_embedded_cuesheet = true; id3->embedded_cuesheet.pos = lseek(file.fd, 0, SEEK_CUR) - read_len; id3->embedded_cuesheet.size = len; id3->embedded_cuesheet.encoding = CHAR_ENC_UTF_8; } else { len = parse_tag(name, id3->path, id3, buf, buf_remaining, TAGTYPE_VORBIS); } buf += len; buf_remaining -= len; } /* Skip to the end of the block (needed by FLAC) */ if (file.packet_remaining) { if (file_read(&file, NULL, file.packet_remaining) < 0) { return 0; } } return comment_size; }
exception_t* benchmark(key256_t* key, char* input_filepath, enum algorithm algorithm, enum mode mode, enum encryption encryption, benchmark_run_t* benchmark_run ) { char* function_name = "benchmark()"; exception_t* exception; block128_t* blocks; file_t file; struct timespec clock_begin; struct timespec clock_elapsed; struct timespec clock_end; long long block_count; size_t buffer_size; // Validate parameters. if ( key == NULL ) { return exception_throw("key was NULL.", function_name); } if ( input_filepath == NULL ) { return exception_throw("input_filepath was NULL.", function_name); } if ( benchmark_run == NULL ) { return exception_throw("benchmark_run was NULL.", function_name); } // Open input file. if ( encryption == ENCRYPT ) { exception = file_init(input_filepath, UNENCRYPTED, &file); } else if ( encryption == DECRYPT ) { exception = file_init(input_filepath, ENCRYPTED, &file); } else { return exception_throw("Unhandled encryption parameter.", function_name); } if ( exception != NULL ) { return exception_append(exception, function_name); } // Get number of blocks in file. exception = file_get_block_count(&file, &block_count); if ( exception != NULL ) { return exception_append(exception, function_name); } // Read data from file. fprintf(stdout, "Reading. "); fflush(stdout); exception = file_read(&file, 0, block_count, &blocks); if ( exception != NULL ) { return exception_append(exception, function_name); } // Print message for the user. if ( encryption == ENCRYPT ) { fprintf(stdout, "Encrypting. "); } else if ( encryption == DECRYPT ) { fprintf(stdout, "Decrypting. "); } else { return exception_throw("Invalid encryption parameter.", function_name); } fflush(stdout); // Get begin time. if ( clock_gettime(CLOCK_REALTIME, &clock_begin) == -1 ) { return exception_throw("Unable to get begin time.", function_name); } // Call the algorithm. switch(algorithm) { case AES: return exception_throw("Not implemented. Sorry!", function_name); break; case SERPENT: exception = serpent(key, blocks, block_count, mode, encryption, &buffer_size); break; case TWOFISH: exception = twofish(key, blocks, block_count, mode, encryption, &buffer_size); break; default: return exception_throw("Unrecognized algorithm.", function_name); break; } if ( exception != NULL ) { return exception_append(exception, function_name); } // Get end time. if ( clock_gettime(CLOCK_REALTIME, &clock_end) == -1 ) { return exception_throw("Unable to get end time.", function_name); } // Write data to file. fprintf(stdout, "Writing. "); fflush(stdout); exception = file_write(&file, 0, block_count, blocks); if ( exception != NULL ) { return exception_append(exception, function_name); } // Close input file. exception = file_free(&file); if ( exception != NULL ) { return exception_append(exception, function_name); } // Calculate execution time. clock_elapsed.tv_sec = clock_end.tv_sec - clock_begin.tv_sec; clock_elapsed.tv_nsec = clock_end.tv_nsec - clock_begin.tv_nsec; if ( clock_elapsed.tv_nsec < 0 ) { clock_elapsed.tv_nsec += 1000000000; clock_elapsed.tv_sec -= 1; } // Assign output parameters. benchmark_run->time_elapsed.tv_sec = clock_elapsed.tv_sec; benchmark_run->time_elapsed.tv_nsec = clock_elapsed.tv_nsec; benchmark_run->buffer_size = buffer_size; // Return success. return NULL; }
static int socket_accept4(struct file *f, struct sockaddr *addr, int *addrlen, int flags) { struct socket_file *socket = (struct socket_file *)f; WaitForSingleObject(socket->mutex, INFINITE); struct sockaddr_storage addr_storage; int addr_storage_len; int r; while ((r = socket_wait_event(socket, FD_ACCEPT, 0)) == 0) { SOCKET socket_handle; addr_storage_len = sizeof(struct sockaddr_storage); if ((socket_handle = accept(socket->socket, (struct sockaddr *)&addr_storage, &addr_storage_len)) != SOCKET_ERROR) { /* Create a new socket */ HANDLE event_handle = init_socket_event(socket_handle); if (!event_handle) { closesocket(socket_handle); log_error("init_socket_event() failed."); r = -L_ENFILE; break; } HANDLE mutex; SECURITY_ATTRIBUTES attr; attr.nLength = sizeof(SECURITY_ATTRIBUTES); attr.lpSecurityDescriptor = NULL; attr.bInheritHandle = TRUE; mutex = CreateMutexW(&attr, FALSE, NULL); struct socket_file *conn_socket = (struct socket_file *)kmalloc(sizeof(struct socket_file)); file_init(&conn_socket->base_file, &socket_ops, 0); conn_socket->socket = socket_handle; conn_socket->event_handle = event_handle; conn_socket->mutex = mutex; conn_socket->shared = (struct socket_file_shared *)kmalloc_shared(sizeof(struct socket_file_shared)); conn_socket->shared->af = socket->shared->af; conn_socket->shared->type = socket->shared->type; conn_socket->shared->events = 0; conn_socket->shared->connect_error = 0; if (flags & O_NONBLOCK) conn_socket->base_file.flags |= O_NONBLOCK; r = vfs_store_file((struct file *)conn_socket, 0); if (r < 0) vfs_release((struct file *)conn_socket); /* Translate address back to Linux format */ if (addr && addrlen) { if (socket->shared->af == LINUX_AF_UNIX) { /* Set addr to unnamed */ struct sockaddr_un *addr_un = (struct sockaddr_un *)addr; *addrlen = sizeof(addr_un->sun_family); } else { *addrlen = translate_socket_addr_to_linux(&addr_storage, addr_storage_len); memcpy(addr, &addr_storage, *addrlen); } } break; } int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) { log_warning("accept() failed, error code: %d", err); r = translate_socket_error(err); break; } InterlockedAnd(&socket->shared->events, ~FD_ACCEPT); } ReleaseMutex(socket->mutex); return r; }
int main(int argc, char *argv[]) { enum { MAX_RETRIES = 100 }; enum { SLEEP_US = 1000 }; bool attach = false; _xcc_status cc; bool client = false; int count; int count_read; int count_written; bool dif = false; double dloop; double dms; double dsec; int err; bool exec = false; int ferr; bool fin = false; MS_Mon_Process_Info_Type info; MS_Mon_Process_Info_Type *infop; int inx; int inx2; int inx3; short len; short lerr; short lerr2; int loop = 10; int max; int nid; pid_t pid; int sargc; ssize_t size; int snid; int spid; bool startup = false; xzsys_ddl_smsg_def *sys_msgp = (xzsys_ddl_smsg_def *) recv_buffer; int sys_msg; int sys_msg_count; bool verbose = false; TAD zargs[] = { { "-attach", TA_Bool, TA_NOMAX, &attach }, { "-client", TA_Bool, TA_NOMAX, &client }, { "-dif", TA_Bool, TA_NOMAX, &dif }, { "-exec", TA_Bool, TA_NOMAX, &exec }, { "-loop", TA_Int, TA_NOMAX, &loop }, { "-maxsp", TA_Int, TA_NOMAX, &maxsp }, { "-server", TA_Ign, TA_NOMAX, NULL }, { "-startup", TA_Bool, TA_NOMAX, &startup }, { "-trace", TA_Bool, TA_NOMAX, &trace }, { "-v", TA_Bool, TA_NOMAX, &verbose }, { "-verbose", TA_Ign, TA_NOMAX, NULL }, { "", TA_End, TA_NOMAX, NULL } }; arg_proc_args(zargs, false, argc, argv); sprintf(fifo1, "%s-%s", FIFO1, getenv("USER")); sprintf(fifo2, "%s-%s", FIFO2, getenv("USER")); if (trace) msg_init_trace(); if (exec) return 0; if (startup) { err = fifo_open(fifo1, O_WRONLY); assert(err != -1); ffds[1] = err; err = fifo_open(fifo2, O_RDONLY); assert(err != -1); ffds[0] = err; if (trace) trace_printf("cli: writing fifo\n"); size = write(ffds[1], recv_buffer, 1); if (trace) trace_printf("cli: fifo write, size=%d\n", (int) size); assert(size == 1); if (trace) trace_printf("cli: fifo written\n"); close(ffds[1]); return 0; } if (attach) ferr = file_init_attach(&argc, &argv, false, NULL); else ferr = file_init(&argc, &argv); TEST_CHK_FEOK(ferr); util_test_start(client); ferr = msg_mon_process_startup(true); // system messages util_check("msg_mon_process_startup", ferr); ferr = msg_mon_get_my_process_name(procname, BUFSIZ); util_check("msg_mon_get_my_process_name", ferr); ferr = msg_mon_get_process_info(procname, &nid, &pid); TEST_CHK_FEOK(ferr); if (trace) trace_printf("proc=%s, nid=%d, pid=%d\n", procname, nid, pid); dloop = (double) loop; for (inx = 0; inx < T_MAX; inx++) t_elapsed[inx] = 0.0; if (client) { printf("loop=%d, maxsp=%d\n", loop, maxsp); sargc = argc; assert(sargc < MAX_ARGS); for (inx2 = 0; inx2 < argc; inx2++) { if (strcmp(argv[inx2], "-client") == 0) sargv[inx2] = (char *) "-server"; else sargv[inx2] = argv[inx2]; if (strcmp(argv[inx2], "-attach") == 0) sargv[inx2] = (char *) "-server"; } sargv[argc] = NULL; sprintf(sprog, "%s/%s", getenv("PWD"), argv[0]); time_start(T_TOTAL); for (inx = 0; inx < loop; inx += maxsp) { if (dif) snid = -1; else snid = nid; max = loop - inx; if (max > maxsp) max = maxsp; for (inx2 = 0; inx2 < max; inx2++) sname[inx2][0] = 0; // mon picks name if (trace) trace_printf("cli: newproc, inx=%d\n", inx); time_start(T_NEWPROC); for (inx2 = 0; inx2 < max; inx2++) { ferr = msg_mon_start_process(sprog, // prog sname[inx2], // name sname[inx2], // ret_name sargc, // argc sargv, // argv TPT_REF2(sphandle,inx2),// phandle false, // open &soid[inx2], // oid MS_ProcessType_Generic, // type 0, // priority false, // debug false, // backup &snid, // nid &spid, // pid NULL, // infile NULL); // outfile TEST_CHK_FEOK(ferr); } time_stop(T_NEWPROC); time_elapsed(T_NEWPROC); // wait here until processes are 'up' // so that open timing is correct inx3 = 0; for (inx2 = 0; inx2 < max; inx2++) { ferr = msg_mon_get_process_info_detail(sname[inx2], &info); TEST_CHK_FEOK(ferr); if (info.state != MS_Mon_State_Up) { inx3++; if (inx3 > MAX_RETRIES) { printf("process %s did not enter 'UP' state\n", sname[inx2]); assert(inx3 < MAX_RETRIES); } usleep(SLEEP_US); inx2--; continue; } else inx3 = 0; } if (trace) trace_printf("cli: open, inx=%d\n", inx); time_start(T_OPEN); for (inx2 = 0; inx2 < max; inx2++) { if (trace) trace_printf("cli: opening inx=%d, name=%s\n", inx, sname[inx2]); len = (short) strlen(sname[inx2]); ferr = BFILE_OPEN_(sname[inx2], len, &sfilenum[inx2], 0, 0, 0, 0, 0, 0, 0); if (trace) trace_printf("cli: open, inx=%d, name=%s, ferr=%d\n", inx, sname[inx2], ferr); TEST_CHK_FEOK(ferr); } time_stop(T_OPEN); time_elapsed(T_OPEN); if (trace) trace_printf("cli: procinfo, inx=%d\n", inx); time_start(T_PROCINFO); for (inx2 = 0; inx2 < max; inx2++) { ferr = msg_mon_get_process_info_detail(sname[inx2], &info); TEST_CHK_FEOK(ferr); } time_stop(T_PROCINFO); time_elapsed(T_PROCINFO); if (trace) trace_printf("cli: procinfo-type, inx=%d\n", inx); time_start(T_PROCINFO_TYPE); ferr = msg_mon_get_process_info_type(MS_ProcessType_Generic, &count, MAX_SRV, infotype); TEST_CHK_FEOK(ferr); time_stop(T_PROCINFO_TYPE); time_elapsed(T_PROCINFO_TYPE); if (verbose) { for (inx2 = 0; inx2 < count; inx2++) { infop = &infotype[inx2]; char s_em = infop->event_messages ? 'E' : '-'; char s_sm = infop->system_messages ? 'S' : '-'; char s_pr = infop->pending_replication ? 'R' : '-'; char s_pd = infop->pending_delete ? 'D' : '-'; char s_s = infop->state == MS_Mon_State_Up ? 'A' : 'U'; char s_o = infop->opened ? 'O' : '-'; char s_p = infop->paired ? 'P' : infop->backup ? 'B' : '-'; printf("%3.3d,%8.8d %3.3d %d %c%c%c%c%c%c%c %-11s %-11s %-15s\n", infop->nid, infop->pid, infop->priority, infop->state, s_em, s_sm, s_pr, s_pd, s_s, s_o, s_p, infop->process_name, infop->parent_name, infop->program); } } if (trace) trace_printf("cli: close, inx=%d\n", inx); time_start(T_CLOSE); for (inx2 = 0; inx2 < max; inx2++) { ferr = BFILE_CLOSE_(sfilenum[inx2]); TEST_CHK_FEOK(ferr); } time_stop(T_CLOSE); time_elapsed(T_CLOSE); // re-open/close for (inx2 = 0; inx2 < max; inx2++) { if (trace) trace_printf("cli: re-opening inx=%d, name=%s\n", inx, sname[inx2]); len = (short) strlen(sname[inx2]); ferr = BFILE_OPEN_(sname[inx2], len, &sfilenum[inx2], 0, 0, 0, 0, 0, 0, 0); TEST_CHK_FEOK(ferr); } if (trace) trace_printf("cli: re-close, inx=%d\n", inx); for (inx2 = 0; inx2 < max; inx2++) { ferr = BFILE_CLOSE_(sfilenum[inx2]); TEST_CHK_FEOK(ferr); } if (trace) trace_printf("cli: newproc-forkexec, inx=%d\n", inx); sargc = 2; sargv[0] = argv[0]; sargv[1] = (char *) "-exec"; if (trace) sargv[sargc++] = (char *) "-trace"; sargv[sargc] = NULL; time_start(T_FORKEXEC); for (inx2 = 0; inx2 < max; inx2++) { pid = fork(); assert(pid >= 0); if (pid == 0) { // child err = execv(sprog, sargv); assert(err == 0); } } time_stop(T_FORKEXEC); time_elapsed(T_FORKEXEC); if (trace) trace_printf("cli: newproc-forkexec-su, inx=%d\n", inx); sargc = 2; sargv[0] = argv[0]; sargv[1] = (char *) "-startup"; if (trace) sargv[sargc++] = (char *) "-trace"; sargv[sargc] = NULL; time_start(T_FORKEXEC_SU); for (inx2 = 0; inx2 < max; inx2++) { fifo_create(fifo1, fifo2); pid = fork(); assert(pid >= 0); if (pid > 0) { // parent err = fifo_open(fifo1, O_RDONLY); assert(err != -1); ffds[0] = err; err = fifo_open(fifo2, O_WRONLY); assert(err != -1); ffds[1] = err; if (trace) trace_printf("cli: reading fifo, inx=%d\n", inx2); size = ::read(ffds[0], recv_buffer, 1); if (trace) trace_printf("cli: fifo read, size=%d\n", (int) size); assert(size == 1); if (trace) trace_printf("cli: fifo read, inx=%d\n", inx2); ::read(ffds[0], recv_buffer, 1); err = fifo_close(ffds[0]); assert(err == 0); err = fifo_close(ffds[1]); assert(err == 0); fifo_destroy(fifo1, fifo1); } else { // child err = execv(sprog, sargv); assert(err == 0); } } fifo_destroy(fifo2, fifo2); time_stop(T_FORKEXEC_SU); time_elapsed(T_FORKEXEC_SU); } } else { sys_msg_count = 0; time_start(T_TOTAL); ferr = BFILE_OPEN_((char *) "$RECEIVE", 8, &filenumr, 0, 0, 0, 1, 0); // sys msgs TEST_CHK_FEOK(ferr); for (inx = 0; !fin; inx++) { if (trace) trace_printf("srv: readupdate, inx=%d\n", inx); cc = BREADUPDATEX(filenumr, recv_buffer, 4, &count_read, 0); sys_msg = _xstatus_ne(cc); if (trace && sys_msg) trace_printf("srv: rcvd sys msg=%d\n", sys_msgp->u_z_msg.z_msgnumber[0]); if (sys_msg) { sys_msg_count++; inx--; } lerr2 = BFILE_GETINFO_(filenumr, &lerr); TEST_CHK_FEIGNORE(lerr2); if (trace) trace_printf("srv: reply, inx=%d\n", inx); cc = BREPLYX(recv_buffer, (unsigned short) 0, &count_written, 0, XZFIL_ERR_OK); TEST_CHK_CCEQ(cc); if (sys_msg_count >= 4) fin = true; } } time_stop(T_TOTAL); time_elapsed(T_TOTAL); if (client) { dsec = time_sec(T_TOTAL); dms = dsec * 1000.0; printf("elapsed=%f\n", dms); printf("open/close/newprocess/processinfo/forkexec=%d\n", loop); dsec = time_sec(T_OPEN); dms = dsec * 1000.0; printf("open : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_CLOSE); dms = dsec * 1000.0; printf("close : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_PROCINFO); dms = dsec * 1000.0; printf("procinfo : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_PROCINFO_TYPE); dms = dsec * 1000.0; printf("procinfo-type : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_NEWPROC); dms = dsec * 1000.0; printf("newproc : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_FORKEXEC); dms = dsec * 1000.0; printf("forkexec : total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); dsec = time_sec(T_FORKEXEC_SU); dms = dsec * 1000.0; printf("forkexec-startup: total-time=%f ms, time/loop=%f ms, ops/sec=%f\n", dms, dms / dloop, dloop / dsec); } ferr = msg_mon_process_shutdown(); TEST_CHK_FEOK(ferr); util_test_finish(client); return 0; }
void file_reinit(void) { disk_init(); file_init(); }
int main_real(int argc, char **argv) { dbg(0, "in main loop 001 ##########################\n"); xmlerror *error = NULL; char *config_file = NULL; int opt; char *cp; struct attr navit; GList *list = NULL, *li; main_argc = argc; main_argv = argv; //dbg(0, "in main loop 002 ##########################\n"); #ifdef HAVE_GLIB event_glib_init(); //dbg(0,"in main loop 003 ##########################\n"); #else _g_slice_thread_init_nomessage(); //dbg(0, "in main loop 004 ##########################\n"); #endif atom_init(); main_init(argv[0]); main_init_nls(); debug_init(argv[0]); // ?? cp = getenv("NAVIT_LOGFILE"); if (cp) { debug_set_logfile(cp); } #ifdef HAVE_API_WIN32_CE else { debug_set_logfile("/Storage Card/navit.log"); } #endif //dbg(0, "in main loop 005 ##########################\n"); file_init(); //dbg(0, "in main loop 006 ##########################\n"); #ifndef USE_PLUGINS //dbg(0, "in main loop 007 ##########################\n"); builtin_init(); #endif //dbg(0, "in main loop 008 ##########################\n"); route_init(); //dbg(0, "in main loop 008.1 ##########################\n"); navigation_init(); //dbg(0, "in main loop 008.2 ##########################\n"); tracking_init(); //dbg(0, "in main loop 008.3 ##########################\n"); search_init(); //dbg(0, "in main loop 008.4 ##########################\n"); linguistics_init(); //dbg(0, "in main loop 0014 ##########################\n"); config_file = NULL; #ifdef HAVE_GETOPT_H opterr=0; //don't bomb out on errors. #endif /* _MSC_VER */ if (argc > 1) { /* DEVELOPPERS : don't forget to update the manpage if you modify theses options */ while ((opt = getopt(argc, argv, ":hvc:d:")) != -1) { switch (opt) { case 'h': print_usage(); exit(0); break; case 'v': printf("%s %s\n", "navit", version); exit(0); break; case 'c': printf("config file n is set to `%s'\n", optarg); config_file = optarg; break; case 'd': printf("TODO Verbose option is set to `%s'\n", optarg); break; #ifdef HAVE_GETOPT_H case ':': fprintf(stderr, "navit: Error - Option `%c' needs a value\n", optopt); print_usage(); exit(1); break; case '?': fprintf(stderr, "navit: Error - No such option: `%c'\n", optopt); print_usage(); exit(1); #endif } } // use 1st cmd line option that is left for the config file if (optind < argc) config_file = argv[optind]; } // if config file is explicitely given only look for it, otherwise try std paths //if (config_file) //{ // list = g_list_append(list, g_strdup(config_file)); //} //else //{ dbg(0, "navit_share_dir=%s\n", navit_share_dir); list = g_list_append(list, g_strjoin(NULL, navit_share_dir, "/navit.xml", NULL)); //list = g_list_append(list, g_strdup("navit.xml")); #ifdef HAVE_API_ANDROID // **disabled** // new preferred location (the new one should have priority over the legacy!) // **disabled** // list = g_list_append(list,g_strdup("/sdcard/zanavi/navit.xml")); #endif //list = g_list_append(list, g_strjoin(NULL, getenv("NAVIT_SHAREDIR"), "/navit.xml", NULL)); #ifndef _WIN32 //list = g_list_append(list, g_strdup("/etc/navit/navit.xml")); #endif //} li = list; for (;;) { if (li == NULL) { // We have not found an existing config file from all possibilities dbg(0, "No config file navit.xml, navit.xml.local found\n"); return 1; } // Try the next config file possibility from the list config_file = li->data; if (file_exists(config_file)) { break; } else { g_free(config_file); } li = g_list_next(li); } // ############### load XML config file, and call all the init/new functions ################ // ############### load XML config file, and call all the init/new functions ################ // ############### load XML config file, and call all the init/new functions ################ clock_t s_ = debug_measure_start(); if (!config_load(config_file, &error)) { } debug_mrp("load and init xmlconfig:", debug_measure_end(s_)); // ############### load XML config file, and call all the init/new functions ################ // ############### load XML config file, and call all the init/new functions ################ // ############### load XML config file, and call all the init/new functions ################ while (li) { g_free(li->data); li = g_list_next(li); } g_list_free(list); if (!config_get_attr(config, attr_navit, &navit, NULL) && !config_empty_ok) { dbg(0, "No instance has been created, exiting\n"); exit(1); } dbg(0, "in main loop 026 ##########################\n"); event_main_loop_run(); dbg(0, "after main loop ##########################"); #ifndef HAVE_API_ANDROID debug_finished(); #endif return 0; }