Ejemplo n.º 1
0
int main(int c, char **v, char **env)
   {int i, nt, ntmx, rv;

    SC_exe_init_api();

    nt = -1;

    for (i = 1; i < c; i++)
        {if (strcmp(v[i], "-h") == 0)
            {printf("\nUsage: tscrtr [-h] [-t #]\n");
	     printf("    h  this help message\n");
	     printf("    t  number of threads to use\n");
	     printf("\n");
	     exit(1);}

	 else if (strcmp(v[i], "-t") == 0)
	    nt = SC_stoi(v[++i]);};

/*    ntmx = SC_get_ncpu(); */
    ntmx = 16;
    nt   = min(nt, ntmx);
    nt   = max(nt, 1);

    SC_setup_sig_handlers(sig_handler, NULL, 0, TRUE);

    if (SETJMP(cpu) == 0)
       rv = driver(nt);
    else
       rv = 0;

    return(rv);}
Ejemplo n.º 2
0
/* Rexx command line interface */
ULONG
RexxInterface(PRXSTRING rxCmd, PUSHORT pusErr, PRXSTRING rxRc)
{
    int rc;
    static JMP_BUF keepenv;
    int cmdlen;

    memcpy(keepenv, command_line_env, sizeof(JMP_BUF));
    if (!SETJMP(command_line_env, 1)) {
	/* Set variable gp_input_line.
	   Watch out for line length of NOT_ZERO_TERMINATED strings ! */
	cmdlen = rxCmd->strlength + 1;
	/* FIXME HBB 20010121: 3rd argument doesn't make sense. Either
	 * this should be gp_input_line_len, or it shouldn't use
	 * safe_strncpy(), here */
	safe_strncpy(gp_input_line, rxCmd->strptr, cmdlen);
	gp_input_line[cmdlen] = NUL;
	rc = do_line();
	*pusErr = RXSUBCOM_OK;
	rxRc->strptr[0] = rc + '0';
	rxRc->strptr[1] = NUL;
	rxRc->strlength = strlen(rxRc->strptr);
    } else {
/*
   We end up here when bail_to_command_line() is called.
   Therefore sometimes this call should be avoided when
   executing a REXX program (e.g. 'Cancel' from
   PM GUI after a 'pause -1' command)
*/
	*pusErr = RXSUBCOM_ERROR;
	RexxSetHalt(getpid(), 1);
    }
    memcpy(command_line_env, keepenv, sizeof(JMP_BUF));
    return 0;
}
Ejemplo n.º 3
0
Rboolean R_ToplevelExec(void (*fun)(void *), void *data)
{
    RCNTXT thiscontext;
    RCNTXT * volatile saveToplevelContext;
    volatile SEXP topExp, oldHStack;
    Rboolean result;


    PROTECT(topExp = R_CurrentExpr);
    PROTECT(oldHStack = R_HandlerStack);
    R_HandlerStack = R_NilValue;
    saveToplevelContext = R_ToplevelContext;

    begincontext(&thiscontext, CTXT_TOPLEVEL, R_NilValue, R_GlobalEnv,
                 R_BaseEnv, R_NilValue, R_NilValue);
    if (SETJMP(thiscontext.cjmpbuf))
        result = FALSE;
    else {
        R_GlobalContext = R_ToplevelContext = &thiscontext;
        fun(data);
        result = TRUE;
    }
    endcontext(&thiscontext);

    R_ToplevelContext = saveToplevelContext;
    R_CurrentExpr = topExp;
    R_HandlerStack = oldHStack;
    UNPROTECT(2);

    return result;
}
Ejemplo n.º 4
0
void run_Rmainloop(void)
{
    /* Here is the real R read-eval-loop. */
    /* We handle the console until end-of-file. */
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    R_ReplConsole(R_GlobalEnv, 0, 0);
    end_Rmainloop(); /* must go here */
}
Ejemplo n.º 5
0
void R_ReplDLLinit(void)
{
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    R_IoBufferWriteReset(&R_ConsoleIob);
    prompt_type = 1;
    DLLbuf[0] = DLLbuf[CONSOLE_BUFFER_SIZE] = '\0';
    DLLbufp = DLLbuf;
}
Ejemplo n.º 6
0
/* New version used when not in -o mode. The epilog() in master.c is
 * supposed to return an array of files (castles in 2.4.5) to load. The array
 * returned by apply() will be freed at next call of apply(), which means that
 * the ref count has to be incremented to protect against deallocation.
 *
 * The master object is asked to do the actual loading.
 */
void preload_objects (int eflag)
{
    VOLATILE array_t *prefiles;
    svalue_t *ret;
    VOLATILE int ix;
    error_context_t econ;

    save_context(&econ);
    if (SETJMP(econ.context)) {
        restore_context(&econ);
        pop_context(&econ);
        return;
    }
    push_number(eflag);
    ret = apply_master_ob(APPLY_EPILOG, 1);
    pop_context(&econ);
    if ((ret == 0) || (ret == (svalue_t *)-1) || (ret->type != T_ARRAY))
        return;
    else
        prefiles = ret->u.arr;
    if ((prefiles == 0) || (prefiles->size < 1))
        return;

    debug_message("\nLoading preloaded files ...\n");
    prefiles->ref++;
    ix = 0;
    /* in case of an error, effectively do a 'continue' */
    save_context(&econ);
    if (SETJMP(econ.context)) {
        restore_context(&econ);
        ix++;
    }
    for ( ; ix < prefiles->size; ix++) {
        if (prefiles->item[ix].type != T_STRING)
            continue;

        set_eval(max_cost);

        push_svalue(((array_t *)prefiles)->item + ix);
        (void) apply_master_ob(APPLY_PRELOAD, 1);
    }
    free_array((array_t *)prefiles);
    pop_context(&econ);
}       /* preload_objects() */
Ejemplo n.º 7
0
static void R_LoadProfile(FILE *fparg, SEXP env)
{
    FILE * volatile fp = fparg; /* is this needed? */
    if (fp != NULL) {
	if (! SETJMP(R_Toplevel.cjmpbuf)) {
	    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
	    R_ReplFile(fp, env);
	}
	fclose(fp);
    }
}
Ejemplo n.º 8
0
/*
  Return starting address of stack segment.
*/
long
stack_start_addr()
{
	jmp_buf env;
	unsigned long addr;

	(void)SETJMP(env);

	addr = (long)JMP_BUF_SP(env);
	PTR_DECRYPT(addr);

	return addr & PAGE_MASK;
}
Ejemplo n.º 9
0
//Unknown exception handler. And its used to initialization.
void unknown_exception_handler()
{
	//is inited seh?
	if (!g_seh_inited)
	{
		//no mark to inited.
		g_seh_inited=1;
		memset(g_invalid_handler,0,sizeof(SIZEOFJMPBUF));
		//capture invalid exception handler location.
		SETJMP(g_invalid_handler);
	}

	//OUT OF SEH_TRY exceptions comes here.
}
Ejemplo n.º 10
0
SCM_EXPORT ScmObj
scm_call_with_current_continuation(ScmObj proc, ScmEvalState *eval_state)
{
    volatile ScmObj cont, ret;
    struct scm_continuation_frame cont_frame;

    cont_frame.dyn_ext = l_current_dynamic_extent;
    cont_frame.ret_val = SCM_UNDEF;
#if SCM_USE_BACKTRACE
    cont_frame.trace_stack = l_trace_stack;
#endif
    cont = MAKE_CONTINUATION();
    CONTINUATION_SET_FRAME(cont, &cont_frame);
#if SCM_NESTED_CONTINUATION_ONLY
    continuation_stack_push(cont);
#endif

    if (SETJMP(cont_frame.c_env)) {
        /* returned back to the original continuation */
        /* Don't refer cont because it may already be invalidated by
         * continuation_stack_unwind(). */
#if SCM_USE_BACKTRACE
        l_trace_stack = cont_frame.trace_stack;
#endif

        enter_dynamic_extent(cont_frame.dyn_ext);

        eval_state->ret_type = SCM_VALTYPE_AS_IS;
        return cont_frame.ret_val;
    } else {
#if SCM_NESTED_CONTINUATION_ONLY
        /* Call proc with current continutation as (proc cont): This call must
         * not be scm_values_applier, to preserve current stack until longjmp()
         * is called. And so this implementation is not properly recursive. */
        eval_state->ret_type = SCM_VALTYPE_AS_IS;
        ret = scm_call(proc, LIST_1(cont));

        /* the continuation expires when this function returned */
        continuation_stack_unwind(cont);
#else
        /* ONLY FOR TESTING: This call is properly recursible, but all
         * continuations are broken and cannot be called, if the continuation
         * is implemented by longjmp(). */
        ret = LIST_3(scm_values_applier, proc, cont);
#endif

        return ret;
    }
}
Ejemplo n.º 11
0
static void Z130_mapcon_internal(CL_FORM *base, CL_FORM *display[])
{
	CONTENV new_cont;
	CL_FORM *caller_base;
	new_cont.bind_top = bind_top;
	new_cont.last = last_cont;
	LOAD_UNIQUE_TAG(ARG(0));
	caller_base = (CL_FORM *)SETJMP(new_cont.jmp_buf);
	if(caller_base == NULL)
	{
		last_cont = &new_cont;
		if(CL_ATOMP(&display[0][1]))
		{
			LOAD_NIL(ARG(0));
		}
		else
		{
			COPY(&display[0][0], ARG(1));
			COPY(&display[0][1], ARG(2));
			COPY(GET_CAR(&display[0][1]), ARG(3));
			COPY(&display[0][1], ARG(4));
			COPY(ARG(4), ARG(5));
			COPY(GET_CDR(ARG(5)), &display[0][1]);
			COPY(&display[0][2], ARG(3));
			display[1] = ARG(0);
			Z131_get_rest_args(ARG(3), display);
			Fapply(ARG(1), 3);
			mv_count = 1;
			Z130_mapcon_internal(ARG(2), display);
			Fnconc(ARG(1), 2);
			COPY(ARG(1), ARG(0));
		}
		RETURN1:;
		last_cont = new_cont.last;
	}
	else
	{
		last_cont = new_cont.last;
		if(EQ(STACK(caller_base, 0), ARG(0)))
		{
			COPY(STACK(caller_base, 1), ARG(0));
		}
		else
		{
			call_cont(caller_base);
		}
	}
}
Ejemplo n.º 12
0
static void fiber_swap(ACL_FIBER *from, ACL_FIBER *to)
{
	if (from->status == FIBER_STATUS_EXITING) {
		size_t slot = from->slot;
		int n = acl_ring_size(&__thread_fiber->dead);

		/* if the cached dead fibers reached the limit,
		 * some will be freed
		 */
		if (n > MAX_CACHE) {
			n -= MAX_CACHE;
			fiber_kick(n);
		}

		if (!from->sys)
			__thread_fiber->count--;

		__thread_fiber->fibers[slot] =
			__thread_fiber->fibers[--__thread_fiber->slot];
		__thread_fiber->fibers[slot]->slot = slot;

		acl_ring_prepend(&__thread_fiber->dead, &from->me);
	}

#ifdef	USE_JMP
	/* use setcontext() for the initial jump, as it allows us to set up
	 * a stack, but continue with longjmp() as it's much faster.
	 */
	if (SETJMP(from->env) == 0) {
		/* context just be used once for set up a stack, which will
		 * be freed in fiber_start. The context in __thread_fiber
		 * was set NULL.
		 */
		if (to->context != NULL)
			setcontext(to->context);
		else
			LONGJMP(to->env);
	}
#else
	if (swapcontext(from->context, to->context) < 0)
		acl_msg_fatal("%s(%d), %s: swapcontext error %s",
			__FILE__, __LINE__, __FUNCTION__, acl_last_serror());
#endif
}
Ejemplo n.º 13
0
/* Call the pike_module_exit() callbacks for the dynamic modules. */
void exit_dynamic_load(void)
{
#ifdef USE_DYNAMIC_MODULES
  struct module_list * volatile tmp;
  JMP_BUF recovery;
  for (tmp = dynamic_module_list; tmp; tmp = tmp->next)
  {
    if(SETJMP(recovery))
      call_handle_error();
    else
      (*tmp->exit)();
    UNSETJMP(recovery);
    free_program(tmp->module_prog);
    tmp->module_prog = NULL;
    free_string(tmp->name);
    tmp->name = NULL;
  }
#endif
}
Ejemplo n.º 14
0
svalue_t *
safe_call_function_pointer (funptr_t * funp, int num_arg)
{
    error_context_t econ;
    svalue_t *ret;

    if (!save_context(&econ))
        return 0;
    if (!SETJMP(econ.context)) {
        ret = call_function_pointer(funp, num_arg);
    } else {
        restore_context(&econ);
        /* condition was restored to where it was when we came in */
        pop_n_elems(num_arg);
        ret = 0;
    }
    pop_context(&econ);
    return ret;
}
Ejemplo n.º 15
0
void backend()
{
    struct timeval timeout;
    int i, nb;
    volatile int first_call = 1;
    int there_is_a_port = 0;
    error_context_t econ;

    debug_message("Initializations complete.\n\n");
    for (i = 0; i < 5; i++) {
        if (external_port[i].port) {
            debug_message("Accepting connections on port %d.\n",
                    external_port[i].port);
            there_is_a_port = 1;
        }
    }

    if (!there_is_a_port)
        debug_message("No external ports specified.\n");

    init_user_conn();   /* initialize user connection socket */
#ifdef SIGHUP
    signal(SIGHUP, startshutdownMudOS);
#endif
    clear_state();
    save_context(&econ);
    if (SETJMP(econ.context))
        restore_context(&econ);
    if (!t_flag && first_call) {
        first_call = 0;
        call_heart_beat();
    }

    while (1) {
        /* Has to be cleared if we jumped out of process_user_command() */
        current_interactive = 0;
        set_eval(max_cost);

        if (obj_list_replace || obj_list_destruct)
            remove_destructed_objects();

        /*
         * shut down MudOS if MudOS_is_being_shut_down is set.
         */
        if (MudOS_is_being_shut_down)
            shutdownMudOS(0);
        if (slow_shut_down_to_do) {
            int tmp = slow_shut_down_to_do;

            slow_shut_down_to_do = 0;
            slow_shut_down(tmp);
        }
        /*
         * select
         */
        make_selectmasks();
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
#ifndef hpux
        nb = select(FD_SETSIZE, &readmask, &writemask, (fd_set *) 0, &timeout);
#else
        nb = select(FD_SETSIZE, (int *) &readmask, (int *) &writemask,
                (int *) 0, &timeout);
#endif
        /*
         * process I/O if necessary.
         */
        if (nb > 0) {
            process_io();
        }
        /*
         * process user commands.
         */
        for (i = 0; process_user_command() && i < max_users; i++)
            ;

        /*
         * call outs
         */
        call_out();
#ifdef PACKAGE_ASYNC
        check_reqs();
#endif
    }
}       /* backend() */
Ejemplo n.º 16
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc' 
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
    using_history();
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n"
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    gnuplot_version, gnuplot_patchlevel, bug_email);
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) {
	    persist_cl = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* this was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     * Failing this, I propose we just make the call and
     * ignore the return : its probably not a big deal
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

#ifdef X11
    /* This call used to be in x11.trm, with the following comment:
     *   Multi-character inputs like escape sequences but also mouse-pasted
     *   text got buffered and therefore didn't trigger the select() function
     *   in X11_waitforinput(). Switching to unbuffered input solved this.
     *   23 Jan 2002 (joze)
     * But switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * The #ifdef X11 is probably unnecessary, but makes the change minimal.
     * Do any non-X platforms suffer from the same problem?
     * EAM - Jan 2004.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0);
    udv_NaN->udv_undef = FALSE;

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

# if defined(_Windows) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    if (argc > 1)
	interactive = noinputfiles = FALSE;
    else
	noinputfiles = TRUE;

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.release);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

#ifdef WGP_CONSOLE
#ifdef CONSOLE_SWITCH_CP
    if (cp_changed && interactive) {
	fprintf(stderr,
	    "\ngnuplot changed the codepage of this console from %i to %i to\n" \
	    "match the graph window. Some characters might only display correctly\n" \
	    "if you change the font to a non-raster type.\n", 
	    cp_input, GetConsoleCP());
    }
#else
    if ((GetConsoleCP() != GetACP()) && interactive) {
	fprintf(stderr,
	    "\nWarning: The codepage of the graph window (%i) and that of the\n" \
	    "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \
	    "characters don't display correctly.\n", 
	    GetACP(), GetConsoleCP());
    }
#endif
#endif

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();  /*  Initialization of color  */
	load_rcfile();
	init_fit();		/* Initialization of fitting module */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    if (argc > 1) {
#ifdef _Windows
	TBOOLEAN noend = persist_cl;
#endif

	/* load filenames given as arguments */
	while (--argc > 0) {
	    ++argv;
	    c_token = 0;
#ifdef _Windows
	    if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0
	       	|| stricmp(*argv, "-persist") == 0)
		noend = TRUE;
	    else
#endif
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));

	    } else if (strcmp(*argv, "-") == 0) {
		interactive = TRUE;
		while (!com_line());
		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		do_string(*argv);

	    } else {
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	    }
	}
#ifdef _Windows
	if (noend) {
	    interactive = TRUE;
	    while (!com_line());
	}
#endif
    } else {
	/* take commands from stdin */
	while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
Ejemplo n.º 17
0
Archivo: frame.c Proyecto: richq/w3m
static int
createFrameFile(struct frameset *f, FILE * f1, Buffer *current, int level,
		int force_reload)
{
    int r, c, t_stack;
    URLFile f2;
#ifdef USE_M17N
    wc_ces charset, doc_charset;
#endif
    char *d_target, *p_target, *s_target, *t_target;
    ParsedURL *currentURL, base;
    MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL;
    int flag;

    if (f == NULL)
	return -1;

    if (level == 0) {
	if (SETJMP(AbortLoading) != 0) {
	    TRAP_OFF;
	    return -1;
	}
	TRAP_ON;
	f->name = "_top";
    }

    if (level > 7) {
	fputs("Too many frameset tasked.\n", f1);
	return -1;
    }

    if (level == 0) {
	fprintf(f1, "<html><head><title>%s</title></head><body>\n",
		html_quote(current->buffername));
	fputs("<table hborder width=\"100%\">\n", f1);
    }
    else
	fputs("<table hborder>\n", f1);

    currentURL = f->currentURL ? f->currentURL : &current->currentURL;
    for (r = 0; r < f->row; r++) {
	fputs("<tr valign=top>\n", f1);
	for (c = 0; c < f->col; c++) {
	    union frameset_element frame;
	    struct frameset *f_frameset;
	    int i = c + r * f->col;
	    char *p = "";
	    int status = R_ST_NORMAL;
	    Str tok = Strnew();
	    int pre_mode = 0;
	    int end_tag = 0;

	    frame = f->frame[i];

	    if (frame.element == NULL) {
		fputs("<td>\n</td>\n", f1);
		continue;
	    }

	    fputs("<td", f1);
	    if (frame.element->name)
		fprintf(f1, " id=\"_%s\"", html_quote(frame.element->name));
	    if (!r)
		fprintf(f1, " width=\"%s\"", f->width[c]);
	    fputs(">\n", f1);

	    flag = 0;
	    if (force_reload) {
		flag |= RG_NOCACHE;
		if (frame.element->attr == F_BODY)
		    unloadFrame(frame.body);
	    }
	    switch (frame.element->attr) {
	    default:
		/* FIXME: gettextize? */
		fprintf(f1, "Frameset \"%s\" frame %d: type unrecognized",
			html_quote(f->name), i + 1);
		break;
	    case F_UNLOADED:
		if (!frame.body->name && f->name) {
		    frame.body->name = Sprintf("%s_%d", f->name, i)->ptr;
		}
		fflush(f1);
		f_frameset = frame_download_source(frame.body,
						   currentURL,
						   current->baseURL, flag);
		if (f_frameset) {
		    deleteFrame(frame.body);
		    f->frame[i].set = frame.set = f_frameset;
		    goto render_frameset;
		}
		/* fall through */
	    case F_BODY:
		init_stream(&f2, SCM_LOCAL, NULL);
		if (frame.body->source) {
		    fflush(f1);
		    examineFile(frame.body->source, &f2);
		}
		if (f2.stream == NULL) {
		    frame.body->attr = F_UNLOADED;
		    if (frame.body->flags & FB_NO_BUFFER)
			/* FIXME: gettextize? */
			fprintf(f1, "Open %s with other method",
				html_quote(frame.body->url));
		    else if (frame.body->url)
			/* FIXME: gettextize? */
			fprintf(f1, "Can't open %s",
				html_quote(frame.body->url));
		    else
			/* FIXME: gettextize? */
			fprintf(f1,
				"This frame (%s) contains no src attribute",
				frame.body->name ? html_quote(frame.body->name)
				: "(no name)");
		    break;
		}
		parseURL2(frame.body->url, &base, currentURL);
		p_target = f->name;
		s_target = frame.body->name;
		t_target = "_blank";
		d_target = TargetSelf ? s_target : t_target;
#ifdef USE_M17N
		charset = WC_CES_US_ASCII;
		if (current->document_charset != WC_CES_US_ASCII)
		    doc_charset = current->document_charset;
		else
		    doc_charset = DocumentCharset;
#endif
		t_stack = 0;
		if (frame.body->type &&
		    !strcasecmp(frame.body->type, "text/plain")) {
		    Str tmp;
		    fprintf(f1, "<pre>\n");
		    while ((tmp = StrmyUFgets(&f2))->length) {
			tmp = convertLine(NULL, tmp, HTML_MODE, &charset,
					  doc_charset);
			fprintf(f1, "%s", html_quote(tmp->ptr));
		    }
		    fprintf(f1, "</pre>\n");
		    UFclose(&f2);
		    break;
		}
		do {
		    int is_tag = FALSE;
		    char *q;
		    struct parsed_tag *tag;

		    do {
			if (*p == '\0') {
			    Str tmp = StrmyUFgets(&f2);
			    if (tmp->length == 0)
				break;
			    tmp = convertLine(NULL, tmp, HTML_MODE, &charset,
					      doc_charset);
			    p = tmp->ptr;
			}
			read_token(tok, &p, &status, 1, status != R_ST_NORMAL);
		    } while (status != R_ST_NORMAL);

		    if (tok->length == 0)
			continue;

		    if (tok->ptr[0] == '<') {
			if (tok->ptr[1] &&
			    REALLY_THE_BEGINNING_OF_A_TAG(tok->ptr))
			    is_tag = TRUE;
			else if (!(pre_mode & (RB_PLAIN | RB_INTXTA |
					       RB_SCRIPT | RB_STYLE))) {
			    p = Strnew_m_charp(tok->ptr + 1, p, NULL)->ptr;
			    tok = Strnew_charp("&lt;");
			}
		    }
		    if (is_tag) {
			if (pre_mode & (RB_PLAIN | RB_INTXTA | RB_SCRIPT |
					RB_STYLE)) {
			    q = tok->ptr;
			    if ((tag = parse_tag(&q, FALSE)) &&
				tag->tagid == end_tag) {
				if (pre_mode & RB_PLAIN) {
				    fputs("</PRE_PLAIN>", f1);
				    pre_mode = 0;
				    end_tag = 0;
				    goto token_end;
				}
				pre_mode = 0;
				end_tag = 0;
				goto proc_normal;
			    }
			    if (strncmp(tok->ptr, "<!--", 4) &&
				(q = strchr(tok->ptr + 1, '<'))) {
				tok = Strnew_charp_n(tok->ptr, q - tok->ptr);
				p = Strnew_m_charp(q, p, NULL)->ptr;
				status = R_ST_NORMAL;
			    }
			    is_tag = FALSE;
			}
			else if (pre_mode & RB_INSELECT) {
			    q = tok->ptr;
			    if ((tag = parse_tag(&q, FALSE))) {
				if ((tag->tagid == end_tag) ||
				    (tag->tagid == HTML_N_FORM)) {
				    if (tag->tagid == HTML_N_FORM)
					fputs("</SELECT>", f1);
				    pre_mode = 0;
				    end_tag = 0;
				    goto proc_normal;
				}
				if (t_stack) {
				    switch (tag->tagid) {
				    case HTML_TABLE:
				    case HTML_N_TABLE:
				      CASE_TABLE_TAG:
					fputs("</SELECT>", f1);
					pre_mode = 0;
					end_tag = 0;
					goto proc_normal;
				    }
				}
			    }
			}
		    }

		  proc_normal:
		    if (is_tag) {
			char *q = tok->ptr;
			int j, a_target = 0;
			ParsedURL url;

			if (!(tag = parse_tag(&q, FALSE)))
			    goto token_end;

			switch (tag->tagid) {
			case HTML_TITLE:
			    fputs("<!-- title:", f1);
			    goto token_end;
			case HTML_N_TITLE:
			    fputs("-->", f1);
			    goto token_end;
			case HTML_BASE:
			    /* "BASE" is prohibit tag */
			    if (parsedtag_get_value(tag, ATTR_HREF, &q)) {
				q = url_encode(remove_space(q), NULL, charset);
				parseURL(q, &base, NULL);
			    }
			    if (parsedtag_get_value(tag, ATTR_TARGET, &q)) {
				if (!strcasecmp(q, "_self"))
				    d_target = s_target;
				else if (!strcasecmp(q, "_parent"))
				    d_target = p_target;
				else
				    d_target = url_quote_conv(q, charset);
			    }
			    Strshrinkfirst(tok, 1);
			    Strshrink(tok, 1);
			    fprintf(f1, "<!-- %s -->", html_quote(tok->ptr));
			    goto token_end;
			case HTML_META:
			    if (parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &q)
				&& !strcasecmp(q, "refresh")) {
				if (parsedtag_get_value(tag, ATTR_CONTENT, &q)
				    ) {
				    Str s_tmp = NULL;
				    int refresh_interval =
					getMetaRefreshParam(q, &s_tmp);
				    if (s_tmp) {
					q = html_quote(s_tmp->ptr);
					fprintf(f1,
						"Refresh (%d sec) <a href=\"%s\">%s</a>\n",
						refresh_interval, q, q);
				    }
				}
			    }
#ifdef USE_M17N
			    if (UseContentCharset &&
				parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &q)
				&& !strcasecmp(q, "Content-Type")
				&& parsedtag_get_value(tag, ATTR_CONTENT, &q)
				&& (q = strcasestr(q, "charset")) != NULL) {
				q += 7;
				SKIP_BLANKS(q);
				if (*q == '=') {
				    wc_ces c;
				    q++;
				    SKIP_BLANKS(q);
				    if ((c = wc_guess_charset(q, 0)) != 0) {
					doc_charset = c;
					charset = WC_CES_US_ASCII;
				    }
				}
			    }
#endif
			    /* fall thru, "META" is prohibit tag */
			case HTML_HEAD:
			case HTML_N_HEAD:
			case HTML_BODY:
			case HTML_N_BODY:
			case HTML_DOCTYPE:
			    /* prohibit_tags */
			    Strshrinkfirst(tok, 1);
			    Strshrink(tok, 1);
			    fprintf(f1, "<!-- %s -->", html_quote(tok->ptr));
			    goto token_end;
			case HTML_TABLE:
			    t_stack++;
			    break;
			case HTML_N_TABLE:
			    t_stack--;
			    if (t_stack < 0) {
				t_stack = 0;
				Strshrinkfirst(tok, 1);
				Strshrink(tok, 1);
				fprintf(f1,
					"<!-- table stack underflow: %s -->",
					html_quote(tok->ptr));
				goto token_end;
			    }
			    break;
			  CASE_TABLE_TAG:
			    /* table_tags MUST be in table stack */
			    if (!t_stack) {
				Strshrinkfirst(tok, 1);
				Strshrink(tok, 1);
				fprintf(f1, "<!-- %s -->",
					html_quote(tok->ptr));
				goto token_end;

			    }
			    break;
			case HTML_SELECT:
			    pre_mode = RB_INSELECT;
			    end_tag = HTML_N_SELECT;
			    break;
			case HTML_TEXTAREA:
			    pre_mode = RB_INTXTA;
			    end_tag = HTML_N_TEXTAREA;
			    break;
			case HTML_SCRIPT:
			    pre_mode = RB_SCRIPT;
			    end_tag = HTML_N_SCRIPT;
			    break;
			case HTML_STYLE:
			    pre_mode = RB_STYLE;
			    end_tag = HTML_N_STYLE;
			    break;
			case HTML_LISTING:
			    pre_mode = RB_PLAIN;
			    end_tag = HTML_N_LISTING;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			case HTML_XMP:
			    pre_mode = RB_PLAIN;
			    end_tag = HTML_N_XMP;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			case HTML_PLAINTEXT:
			    pre_mode = RB_PLAIN;
			    end_tag = MAX_HTMLTAG;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			default:
			    break;
			}
			for (j = 0; j < TagMAP[tag->tagid].max_attribute; j++) {
			    switch (tag->attrid[j]) {
			    case ATTR_SRC:
			    case ATTR_HREF:
			    case ATTR_ACTION:
				if (!tag->value[j])
				    break;
				tag->value[j] =
				    url_encode(remove_space(tag->value[j]),
					       &base, charset);
				tag->need_reconstruct = TRUE;
				parseURL2(tag->value[j], &url, &base);
				if (url.scheme == SCM_UNKNOWN ||
#ifndef USE_W3MMAILER
				    url.scheme == SCM_MAILTO ||
#endif
				    url.scheme == SCM_MISSING)
				    break;
				a_target |= 1;
				tag->value[j] = parsedURL2Str(&url)->ptr;
				parsedtag_set_value(tag,
						    ATTR_REFERER,
						    parsedURL2Str(&base)->ptr);
#ifdef USE_M17N
				if (tag->attrid[j] == ATTR_ACTION &&
				    charset != WC_CES_US_ASCII)
				    parsedtag_set_value(tag,
							ATTR_CHARSET,
							wc_ces_to_charset
							(charset));
#endif
				break;
			    case ATTR_TARGET:
				if (!tag->value[j])
				    break;
				a_target |= 2;
				if (!strcasecmp(tag->value[j], "_self")) {
				    parsedtag_set_value(tag,
							ATTR_TARGET, s_target);
				}
				else if (!strcasecmp(tag->value[j], "_parent")) {
				    parsedtag_set_value(tag,
							ATTR_TARGET, p_target);
				}
				break;
			    case ATTR_NAME:
			    case ATTR_ID:
				if (!tag->value[j])
				    break;
				parsedtag_set_value(tag,
						    ATTR_FRAMENAME, s_target);
				break;
			    }
			}
			if (a_target == 1) {
			    /* there is HREF attribute and no TARGET
			     * attribute */
			    parsedtag_set_value(tag, ATTR_TARGET, d_target);
			}
			if (parsedtag_need_reconstruct(tag))
			    tok = parsedtag2str(tag);
			Strfputs(tok, f1);
		    }
		    else {
			if (pre_mode & RB_PLAIN)
			    fprintf(f1, "%s", html_quote(tok->ptr));
			else if (pre_mode & RB_INTXTA)
			    fprintf(f1, "%s",
				    html_quote(html_unquote(tok->ptr)));
			else
			    Strfputs(tok, f1);
		    }
		  token_end:
		    Strclear(tok);
		} while (*p != '\0' || !iseos(f2.stream));
		if (pre_mode & RB_PLAIN)
		    fputs("</PRE_PLAIN>\n", f1);
		else if (pre_mode & RB_INTXTA)
		    fputs("</TEXTAREA></FORM>\n", f1);
		else if (pre_mode & RB_INSELECT)
		    fputs("</SELECT></FORM>\n", f1);
		else if (pre_mode & (RB_SCRIPT | RB_STYLE)) {
		    if (status != R_ST_NORMAL)
			fputs(correct_irrtag(status)->ptr, f1);
		    if (pre_mode & RB_SCRIPT)
			fputs("</SCRIPT>\n", f1);
		    else if (pre_mode & RB_STYLE)
			fputs("</STYLE>\n", f1);
		}
		while (t_stack--)
		    fputs("</TABLE>\n", f1);
		UFclose(&f2);
		break;
	    case F_FRAMESET:
	      render_frameset:
		if (!frame.set->name && f->name) {
		    frame.set->name = Sprintf("%s_%d", f->name, i)->ptr;
		}
		createFrameFile(frame.set, f1, current, level + 1,
				force_reload);
		break;
	    }
	    fputs("</td>\n", f1);
	}
	fputs("</tr>\n", f1);
    }

    fputs("</table>\n", f1);
    if (level == 0) {
	fputs("</body></html>\n", f1);
	TRAP_OFF;
    }
    return 0;
}
Ejemplo n.º 18
0
/* 
 * StartOS API call.
 * This service is called to start the operating system in a specific mode.
 */
void os_StartOS(AppModeType appmode)
{
	os_ipl save_ipl;
	
	OS_SAVE_IPL(save_ipl);									/* Save IPL on entry so can restore on exit, side-effect: assigns back to save_ipl */
	
	ENTER_KERNEL_DIRECT();								/* Set IPL to kernel level while setting up OS variables etc. */
	OS_API_TRACE_START_OS();
	INIT_STACKCHECK_TO_OFF();							/* Make sure stack checking is turned off so that when/if dispatch() is called there are no stack errors
														 * Note that this requires the kernel stack (i.e. main()'s stack) is big enough to support this call to
														 * StartOS plus a call to dispatch() and the entry into the subsequent task
														 */
#ifndef NDEBUG
	assert_initialized();								/* assert the C runtime startup has setup all vars to startup state */
#endif
	
	/* Saving a jmp_buf (os_startosenv) so that the entire OS can be terminated via a longjmp call inside a ShutdownOS call */
	/* $Req: artf1216 artf1219 $ */
	if (SETJMP(os_startosenv) == 0) {					
														/* This half of the 'if' is the half that is the run-on continuation */
		/* $Req: artf1214 artf1094 $ */
		os_appmode = appmode;							/* Store application mode in which the OS was started */

		/* setup the tasks and alarms that are to be autostarted for the given app mode */													
		start_tasks(appmode);
		
		/* Initialize all counters in the system to start running */
		start_counters();
		
		/* Autostart alarms */
		if(appmode->start_alarms_singleton) {
			appmode->start_alarms_singleton(appmode);
		}

		if(appmode->start_alarms_multi) {
			appmode->start_alarms_multi(appmode);
		}
		
		/* Autostarted schedule tables are autostarted implicitly by the underlying alarms being autostarted */

#ifdef STACK_CHECKING	
		os_curtos = OS_KS_TOP;
#endif

		/* Call startup hook if required to do so */
		/* $Req: artf1215 $ */
		if (os_flags.startuphook) {						/* check if need to call the startuphook handler */
														/* hook needs calling */
			ENABLE_STACKCHECK();						/* enable stack checking */
			/* @todo check that we really need to raise IPL to lock out all interrupts (both CAT1 and CAT2) within the hook */			
			OS_SET_IPL_MAX();							/* raise IPL to lock out all interrupts (both CAT1 and CAT2) within the hook */
			MARK_OUT_KERNEL();							/* drop out of the kernel, keeping IPL at max level  */
			/* $Req: artf1117 $ */
			StartupHook();								/* call the hook routine with IPL set to kernel level and stack checking on */
			MARK_IN_KERNEL();							/* go back into the kernel */
			OS_SET_IPL_KERNEL();						/* set IPL back to kernel level */
			DISABLE_STACKCHECK();						/* disable stack checking */
		}

		/* Start the scheduling activity */
		if (TASK_SWITCH_PENDING(os_curpri)) {
			os_ks_dispatch();
		}
		
		ENABLE_STACKCHECK();
		LEAVE_KERNEL();

		/* now running as the body of the os_idle task, with IPL at level 0 and priority of IDLEPRI */
		/* $Req: artf1116 $ */
		/* Note that interrupts will be enabled prior to here because the os_ks_dispatch() call above
		 * might switch to running autostarted tasks, which will lower interrupts to level 0
		 */		
		for ( ; ; ) {
			os_idle();										/* call the os_idle task entry function */
		}
		
		NOT_REACHED();
	}
	else {
														/* This half of the 'if' is the half that is RETURNING from a longjmp */
														/* We have come back from a ShutdownOS() call */
	}
	
	/* Reached here because ShutdownOS(E_OK) was called.
	 * 
	 * $Req: artf1219 $
	 */
	assert(KERNEL_LOCKED());
	assert(STACKCHECK_OFF());							/* Stack checking turned off prior to longjmp in shutdown() */
		
	/* Would normally stop the counters, reinitialise the kernel variables, etc. in case StartOS() were to be called again,
	 * but OS424 (artf1375) requires that StartOS() doesn't return, but instead goes into an infinite loop.
	 * Similarly, OS425 (artf1376) requires that interrupts are disabled before entering the loop.
	 * 
	 * If StartOS() is ever required to return to caller, see revision 568 of this file (startos.c) for the
	 * original code that did this.
	 * 
	 * $Req: artf1375 $
	 * $Req: artf1376 $
	 */
	OS_SET_IPL_MAX();
	for(;;)
		;
}
Ejemplo n.º 19
0
/* Don't static for INLINE */
void
thrSwitch( Thread t )
{
/*	register Thread	run_thread = ThrRunningThread ; */
  volatile Thread run_thread;
  run_thread = ThrRunningThread;

	run_thread->errno = errno ;
	run_thread->debugFlags = OzDebugFlags ;
	if ( SETJMP(run_thread->context) ) {
		while ( thrDefunctThreads ) {
			register Thread defunct ;
			defunct = thrDefunctThreads ;
			thrDefunctThreads = thrDefunctThreads->next ;
			stkFree( defunct->stack, defunct->stack_size ) ;
			defunct->status = FREE ;
			defunct->next = thrFreeThreads ;
			thrFreeThreads = defunct ;
		}
/*		errno = run_thread->errno ;
		OzDebugFlags = run_thread->debugFlags ;
*/
		return ;			/* to signaled pc */
	}

	ThrRunningThread = t ;
	t->status = RUNNING ;
	errno = t->errno ;
	OzDebugFlags = t->debugFlags ;

	run_thread->sigBlocking = sigBlocking ;
	if (run_thread->sigBlocking && !t->sigBlocking)
		SigDisable() ;
	else if (!run_thread->sigBlocking && t->sigBlocking)
		thrAllocSignalStack( &(t->signal_stack) ) ;

	if (!run_thread->sigBlocking || !t->sigBlocking)
		SIGSTACK(&(t->signal_stack), &(run_thread->signal_stack));
	else if ( t != run_thread ) {
		t->signal_stack = run_thread->signal_stack ;
		run_thread->signal_stack.ss_sp = NULL ;
		SIGSTACK_FLAGS(run_thread->signal_stack) = 0 ;
	}

	sigBlocking = t->sigBlocking;
	if (run_thread->sigBlocking && !t->sigBlocking) {
		thrFreeSignalStack( &(run_thread->signal_stack) );
	} else if (!run_thread->sigBlocking && t->sigBlocking) {
		SigEnable() ;
	}

	if ( t->first ) {	/* first dispatch */
		register void	(*pc)() ;
		register void	*sp ;
#if	defined(SVR4)
	sp = (char *)t->context[1] ;
	pc = (void (*))t->context[2] ;
#else	/* SVR4 */
	sp = (char *)t->context[2] ;
	pc = (void (*))t->context[3] ;
#endif	/* SVR4 */
		t->first = 0 ;
		thrJumpThread( thrStart, pc, ThrExit, sp ) ;
		/* NOT REACHED */
	}
	LONGJMP( t->context, 1 ) ;
	/* NOT REACHED */
}
Ejemplo n.º 20
0
/*
 * docmd - decode the command line and execute a command
 */
static void
docmd(
	const char *cmdline
	)
{
	char *tokens[1+MAXARGS+MOREARGS+2];
	struct parse pcmd;
	int ntok;
	int i, ti;
	int rval;
	struct xcmd *xcmd;

	ai_fam_templ = ai_fam_default;
	/*
	 * Tokenize the command line.  If nothing on it, return.
	 */
	if (strlen(cmdline) >= MAXLINE) {
		fprintf(stderr, "***Command ignored, more than %d characters:\n%s\n",
			MAXLINE - 1, cmdline);
		return;
	}
	tokenize(cmdline, tokens, &ntok);
	if (ntok == 0)
	    return;
	
	/*
	 * Find the appropriate command description.
	 */
	i = findcmd(tokens[0], builtins, opcmds, &xcmd);
	if (i == 0) {
		(void) fprintf(stderr, "***Command `%s' unknown\n",
			       tokens[0]);
		return;
	} else if (i >= 2) {
		(void) fprintf(stderr, "***Command `%s' ambiguous\n",
			       tokens[0]);
		return;
	}
	
	/*
	 * Save the keyword, then walk through the arguments, interpreting
	 * as we go.
	 */
	pcmd.keyword = tokens[0];
	pcmd.nargs = 0;
	ti = 1;
	for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) {
		if ((i+ti) >= ntok) {
			if (!(xcmd->arg[i] & OPT)) {
				printusage(xcmd, stderr);
				return;
			}
			break;
		}
		if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>'))
			break;
		rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]);
		if (rval == -1) {
			ti++;
			continue;
		}
		if (rval == 0)
			return;
		pcmd.nargs++;
		i++;
	}

	/* Any extra args are assumed to be "OPT|NTP_STR". */
	for ( ; i < MAXARGS + MOREARGS;) {
	     if ((i+ti) >= ntok)
		  break;
		rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]);
		if (rval == -1) {
			ti++;
			continue;
		}
		if (rval == 0)
			return;
		pcmd.nargs++;
		i++;
	}

	i += ti;
	if (i < ntok && *tokens[i] == '>') {
		char *fname;

		if (*(tokens[i]+1) != '\0')
		    fname = tokens[i]+1;
		else if ((i+1) < ntok)
		    fname = tokens[i+1];
		else {
			(void) fprintf(stderr, "***No file for redirect\n");
			return;
		}

		current_output = fopen(fname, "w");
		if (current_output == NULL) {
			(void) fprintf(stderr, "***Error opening %s: ", fname);
			perror("");
			return;
		}
	} else {
		current_output = stdout;
	}

	if (interactive) {
		if ( ! SETJMP(interrupt_buf)) {
			jump = 1;
			(xcmd->handler)(&pcmd, current_output);
			jump = 0;
		} else {
			fflush(current_output);
			fputs("\n >>> command aborted <<<\n", stderr);
			fflush(stderr);
		}
	} else {
		jump = 0;
		(xcmd->handler)(&pcmd, current_output);
	}
	if ((NULL != current_output) && (stdout != current_output)) {
		(void)fclose(current_output);
		current_output = NULL;
	}
}
Ejemplo n.º 21
0
void setup_Rmainloop(void)
{
    volatile int doneit;
    volatile SEXP baseEnv;
    SEXP cmd;
    char deferred_warnings[11][250];
    volatile int ndeferred_warnings = 0;

    /* In case this is a silly limit: 2^32 -3 has been seen and
     * casting to intptr_r relies on this being smaller than 2^31 on a
     * 32-bit platform. */
    if(R_CStackLimit > 100000000U) 
	R_CStackLimit = (uintptr_t)-1;
    /* make sure we have enough head room to handle errors */
    if(R_CStackLimit != -1)
	R_CStackLimit = (uintptr_t)(0.95 * R_CStackLimit);

    InitConnections(); /* needed to get any output at all */

    /* Initialize the interpreter's internal structures. */

#ifdef HAVE_LOCALE_H
#ifdef Win32
    {
	char *p, Rlocale[1000]; /* Windows' locales can be very long */
	p = getenv("LC_ALL");
	strncpy(Rlocale, p ? p : "", 1000);
        Rlocale[1000 - 1] = '\0';
	if(!(p = getenv("LC_CTYPE"))) p = Rlocale;
	/* We'd like to use warning, but need to defer.
	   Also cannot translate. */
	if(!setlocale(LC_CTYPE, p))
	    snprintf(deferred_warnings[ndeferred_warnings++], 250,
		     "Setting LC_CTYPE=%s failed\n", p);
	if((p = getenv("LC_COLLATE"))) {
	    if(!setlocale(LC_COLLATE, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_COLLATE=%s failed\n", p);
	} else setlocale(LC_COLLATE, Rlocale);
	if((p = getenv("LC_TIME"))) {
	    if(!setlocale(LC_TIME, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_TIME=%s failed\n", p);
	} else setlocale(LC_TIME, Rlocale);
	if((p = getenv("LC_MONETARY"))) {
	    if(!setlocale(LC_MONETARY, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_MONETARY=%s failed\n", p);
	} else setlocale(LC_MONETARY, Rlocale);
	/* Windows does not have LC_MESSAGES */

	/* We set R_ARCH here: Unix does it in the shell front-end */
	char Rarch[30];
	strcpy(Rarch, "R_ARCH=/");
	strcat(Rarch, R_ARCH);
	putenv(Rarch);
    }
#else /* not Win32 */
    if(!setlocale(LC_CTYPE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_CTYPE failed, using \"C\"\n");
    if(!setlocale(LC_COLLATE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_COLLATE failed, using \"C\"\n");
    if(!setlocale(LC_TIME, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_TIME failed, using \"C\"\n");
#ifdef ENABLE_NLS
    if(!setlocale(LC_MESSAGES, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MESSAGES failed, using \"C\"\n");
#endif
    /* NB: we do not set LC_NUMERIC */
#ifdef LC_MONETARY
    if(!setlocale(LC_MONETARY, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MONETARY failed, using \"C\"\n");
#endif
#ifdef LC_PAPER
    if(!setlocale(LC_PAPER, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_PAPER failed, using \"C\"\n");
#endif
#ifdef LC_MEASUREMENT
    if(!setlocale(LC_MEASUREMENT, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MEASUREMENT failed, using \"C\"\n");
#endif
#endif /* not Win32 */
#endif

    /* make sure srand is called before R_tmpnam, PR#14381 */
    srand(TimeToSeed());

    InitArithmetic();
    InitParser();
    InitTempDir(); /* must be before InitEd */
    InitMemory();
    InitStringHash(); /* must be before InitNames */
    InitNames();
    InitBaseEnv();
    InitGlobalEnv();
    InitDynload();
    InitOptions();
    InitEd();
    InitGraphics();
    InitTypeTables(); /* must be before InitS3DefaultTypes */
    InitS3DefaultTypes();
    
    R_Is_Running = 1;
    R_check_locale();

    /* Initialize the global context for error handling. */
    /* This provides a target for any non-local gotos */
    /* which occur during error handling */

    R_Toplevel.nextcontext = NULL;
    R_Toplevel.callflag = CTXT_TOPLEVEL;
    R_Toplevel.cstacktop = 0;
    R_Toplevel.promargs = R_NilValue;
    R_Toplevel.callfun = R_NilValue;
    R_Toplevel.call = R_NilValue;
    R_Toplevel.cloenv = R_BaseEnv;
    R_Toplevel.sysparent = R_BaseEnv;
    R_Toplevel.conexit = R_NilValue;
    R_Toplevel.vmax = NULL;
    R_Toplevel.nodestack = R_BCNodeStackTop;
#ifdef BC_INT_STACK
    R_Toplevel.intstack = R_BCIntStackTop;
#endif
    R_Toplevel.cend = NULL;
    R_Toplevel.intsusp = FALSE;
    R_Toplevel.handlerstack = R_HandlerStack;
    R_Toplevel.restartstack = R_RestartStack;
    R_Toplevel.srcref = R_NilValue;
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    R_ExitContext = NULL;

    R_Warnings = R_NilValue;

    /* This is the same as R_BaseEnv, but this marks the environment
       of functions as the namespace and not the package. */
    baseEnv = R_BaseNamespace;

    /* Set up some global variables */
    Init_R_Variables(baseEnv);

    /* On initial entry we open the base language package and begin by
       running the repl on it.
       If there is an error we pass on to the repl.
       Perhaps it makes more sense to quit gracefully?
    */

#ifdef RMIN_ONLY
    /* This is intended to support a minimal build for experimentation. */
    if (R_SignalHandlers) init_signal_handlers();
#else
    FILE *fp = R_OpenLibraryFile("base");
    if (fp == NULL)
	R_Suicide(_("unable to open the base package\n"));

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (R_SignalHandlers) init_signal_handlers();
    if (!doneit) {
	doneit = 1;
	R_ReplFile(fp, baseEnv);
    }
    fclose(fp);
#endif

    /* This is where we source the system-wide, the site's and the
       user's profile (in that order).  If there is an error, we
       drop through to further processing.
    */
    R_IoBufferInit(&R_ConsoleIob);
    R_LoadProfile(R_OpenSysInitFile(), baseEnv);
    /* These are the same bindings, so only lock them once */
    R_LockEnvironment(R_BaseNamespace, TRUE);
#ifdef NOTYET
    /* methods package needs to trample here */
    R_LockEnvironment(R_BaseEnv, TRUE);
#endif
    /* At least temporarily unlock some bindings used in graphics */
    R_unLockBinding(R_DeviceSymbol, R_BaseEnv);
    R_unLockBinding(R_DevicesSymbol, R_BaseEnv);
    R_unLockBinding(install(".Library.site"), R_BaseEnv);

    /* require(methods) if it is in the default packages */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".OptRequireMethods"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }

    if (strcmp(R_GUIType, "Tk") == 0) {
	char buf[PATH_MAX];

	snprintf(buf, PATH_MAX, "%s/library/tcltk/exec/Tk-frontend.R", R_Home);
	R_LoadProfile(R_fopen(buf, "r"), R_GlobalEnv);
    }

    /* Print a platform and version dependent greeting and a pointer to
     * the copyleft.
     */
    if(!R_Quiet) PrintGreeting();
 
    R_LoadProfile(R_OpenSiteFile(), baseEnv);
    R_LockBinding(install(".Library.site"), R_BaseEnv);
    R_LoadProfile(R_OpenInitFile(), R_GlobalEnv);

    /* This is where we try to load a user's saved data.
       The right thing to do here is very platform dependent.
       E.g. under Unix we look in a special hidden file and on the Mac
       we look in any documents which might have been double clicked on
       or dropped on the application.
    */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	R_InitialData();
    }
    else {
    	if (! SETJMP(R_Toplevel.cjmpbuf)) {
	    warning(_("unable to restore saved data in %s\n"), get_workspace_name());
	}
    }
    
    /* Initial Loading is done.
       At this point we try to invoke the .First Function.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    /* Try to invoke the .First.sys function, which loads the default packages.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First.sys"));
	R_CurrentExpr = findVar(cmd, baseEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    {
	int i;
	for(i = 0 ; i < ndeferred_warnings; i++)
	    warning(deferred_warnings[i]);
    }
    if (R_CollectWarnings) {
	REprintf(_("During startup - "));
	PrintWarnings();
    }

    /* trying to do this earlier seems to run into bootstrapping issues. */
    R_init_jit_enabled();
    R_Is_Running = 2;
}
Ejemplo n.º 22
0
int main (int argc, char ** argv)
{
    time_t tm;
    int i, new_mudlib = 0, got_defaults = 0;
    char *p;
    char version_buf[80];
#if 0
    int dtablesize;
#endif
    error_context_t econ;

#ifdef PROTO_TZSET
    void tzset();
#endif

#ifdef INCL_LOCALE_H
    setlocale(LC_ALL, "C");
#endif

#if !defined(__SASC) && (defined(AMITCP) || defined(AS225))
    amiga_sockinit();
    atexit(amiga_sockexit);
#endif
#ifdef WRAPPEDMALLOC
    wrappedmalloc_init();
#endif        /* WRAPPEDMALLOC */
#ifdef DEBUGMALLOC
    MDinit();
#endif

#if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL))
    moncontrol(0);
#endif
#ifdef USE_TZSET
    tzset();
#endif
    boot_time = get_current_time();

    const0.type = T_NUMBER;
    const0.u.number = 0;
    const1.type = T_NUMBER;
    const1.u.number = 1;

    /* const0u used by undefinedp() */
    const0u.type = T_NUMBER;
    const0u.subtype = T_UNDEFINED;
    const0u.u.number = 0;

    //fake_prog.program_size = 0; //0 anyway

    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *) &i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10) {
        fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n");
        exit(-1);
    }

    /*
     * An added test: can we do EXTRACT_UCHAR(x++)?
     * (read_number, etc uses it)
     */
    p = (char *) &i;
    (void) EXTRACT_UCHAR(p++);
    if ((p - (char *) &i) != 1) {
        fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n");
        exit(-1);
    }

    /*
     * Check the living hash table size
     */
    if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 &&
            CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 &&
            CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) {
        fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n");
        exit(-1);
    }

#ifdef RAND
    srand(get_current_time());
#else
#  ifdef DRAND48
    srand48(get_current_time());
#  else
#    ifdef RANDOM
    srandom(get_current_time());
#    else
    fprintf(stderr, "Warning: no random number generator specified!\n");
#    endif
#  endif
#endif
    current_time = get_current_time();
    /*
     * Initialize the microsecond clock.
     */
    init_usec_clock();

    /* read in the configuration file */

    got_defaults = 0;
    for (i = 1; (i < argc) && !got_defaults; i++) {
        if (argv[i][0] != '-') {
            set_defaults(argv[i]);
            got_defaults = 1;
        }
    }
    get_version(version_buf);
    if (!got_defaults) {
        fprintf(stderr, "%s for %s.\n", version_buf, ARCH);
        fprintf(stderr, "You must specify the configuration filename as an argument.\n");
        exit(-1);
    }

    printf("Initializing internal tables....\n");
    init_strings();   /* in stralloc.c */
    init_otable();    /* in otable.c */
    init_identifiers();   /* in lex.c */
    init_locals();              /* in compiler.c */

    /*
     * If our estimate is larger than FD_SETSIZE, then we need more file
     * descriptors than the operating system can handle.  This is a problem
     * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both.
     *
     * Unfortunately, since neither MAX_USERS or MAX_EFUN_SOCKS exist any more,
     * we have no clue how many we will need.  This code really should be
     * moved to places where ENFILE/EMFILE is returned.
     */
#if 0
    if (dtablesize > FD_SETSIZE) {
        fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n");
        fprintf(stderr, "         Configuration exceeds system capacity by %d descriptor(s).\n",
                dtablesize - FD_SETSIZE);
    }
#ifdef HAS_SETDTABLESIZE
    /*
     * If the operating system supports setdtablesize() then we can request
     * the number of file descriptors we really need.  First check to see if
     * wee already have enough.  If so dont bother the OS. If not, attempt to
     * allocate the number we estimated above.  There are system imposed
     * limits on file descriptors, so we may not get as many as we asked for.
     * Check to make sure we get enough.
     */
    if (getdtablesize() < dtablesize)
        if (setdtablesize(dtablesize) < dtablesize) {
            fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n");
            fprintf(stderr, "         setdtablesize() could not allocate %d descriptor(s).\n",
                    getdtablesize() - dtablesize);
        }
    /*
     * Just be polite and tell the administrator how many he has.
     */
    fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n",
            getdtablesize(), dtablesize);
#endif
#endif
    time_to_clean_up = TIME_TO_CLEAN_UP;
    max_cost = MAX_COST;
    reserved_size = RESERVED_SIZE;
    max_array_size = MAX_ARRAY_SIZE;
    if(max_array_size > 65535){
        fprintf(stderr, "Maximum array size can not exceed 65535");
        max_array_size = 65535;
    }
    max_buffer_size = MAX_BUFFER_SIZE;
    max_string_length = MAX_STRING_LENGTH;
    mud_lib = (char *) MUD_LIB;
    set_inc_list(INCLUDE_DIRS);
    if (reserved_size > 0)
        reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area");
    for (i = 0; i < sizeof consts / sizeof consts[0]; i++)
        consts[i] = exp(-i / 900.0);
    reset_machine(1);
    /*
     * The flags are parsed twice ! The first time, we only search for the -m
     * flag, which specifies another mudlib, and the D-flags, so that they
     * will be available when compiling master.c.
     */
    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-')
            continue;
        switch (argv[i][1]) {
            case 'D':
                if (argv[i][2]) {
                    lpc_predef_t *tmp = ALLOCATE(lpc_predef_t, TAG_PREDEFINES,
                            "predef");
                    tmp->flag = argv[i] + 2;
                    tmp->next = lpc_predefs;
                    lpc_predefs = tmp;
                    continue;
                }
                fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]);
                exit(-1);
            case 'N':
                no_ip_demon++;
                continue;
#ifdef HAS_CONSOLE
            case 'C':
                has_console = 1;
                continue;
#endif
#ifdef YYDEBUG
            case 'y':
                yydebug = 1;
                continue;
#endif        /* YYDEBUG */
            case 'm':
                mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir");
                if (chdir(mud_lib) == -1) {
                    fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
                    exit(-1);
                }
                new_mudlib = 1;
                break;
        }
    }
    if (!new_mudlib && chdir(mud_lib) == -1) {
        fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
        exit(-1);
    }
    time(&tm);
    debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm));

    add_predefines();
#ifdef WIN32
    _tzset();
#endif

#ifndef NO_IP_DEMON
    if (!no_ip_demon && ADDR_SERVER_IP)
        init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT);
#endif        /* NO_IP_DEMON */

    set_eval(max_cost);

    save_context(&econ);
    if (SETJMP(econ.context)) {
        debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n",
                SIMUL_EFUN, MASTER_FILE);
        exit(-1);
    } else {
        init_simul_efun(SIMUL_EFUN);
        init_master();
    }
    pop_context(&econ);

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            continue;
        } else {
            /*
             * Look at flags. -m and -o has already been tested.
             */
            switch (argv[i][1]) {
                case 'D':
                case 'N':
                case 'm':
                case 'y':
                case 'C':
                    continue;
                case 'f':
                    save_context(&econ);
                    if (SETJMP(econ.context)) {
                        debug_message("Error while calling master::flag(\"%s\"), aborting ...\n", argv[i] + 2);
                        exit(-1);
                    }
                    push_constant_string(argv[i] + 2);
                    apply_master_ob(APPLY_FLAG, 1);
                    if (MudOS_is_being_shut_down) {
                        debug_message("Shutdown by master object.\n");
                        exit(0);
                    }
                    pop_context(&econ);
                    continue;
                case 'e':
                    e_flag++;
                    continue;
                case 'p':
                    external_port[0].port = atoi(argv[i] + 2);
                    continue;
                case 'd':
#ifdef DEBUG_MACRO
                    if (argv[i][2])
                        debug_level_set(&argv[i][2]);
                    else
                        debug_level |= DBG_d_flag;
#else
                    debug_message("Driver must be compiled with DEBUG_MACRO on to use -d.\n");
#endif
                    break;
                case 'c':
                    comp_flag++;
                    continue;
                case 't':
                    t_flag++;
                    continue;
                default:
                    debug_message("Unknown flag: %s\n", argv[i]);
                    exit(-1);
            }
        }
    }
    if (MudOS_is_being_shut_down)
        exit(1);
    if (*(DEFAULT_FAIL_MESSAGE)) {
        char buf[8192];

        strcpy(buf, DEFAULT_FAIL_MESSAGE);
        strcat(buf, "\n");
        default_fail_message = make_shared_string(buf);
    } else
        default_fail_message = "What?\n";
#ifdef PACKAGE_MUDLIB_STATS
    restore_stat_files();
#endif
    preload_objects(e_flag);
#ifdef SIGFPE
    signal(SIGFPE, sig_fpe);
#endif
#ifdef TRAP_CRASHES
#ifdef SIGUSR1
    signal(SIGUSR1, sig_usr1);
#endif
#ifdef SIGUSR2
    signal(SIGUSR2, sig_usr2);
#endif
    signal(SIGTERM, sig_term);
    signal(SIGINT, sig_int);
#ifndef DEBUG
#if defined(SIGABRT)
    signal(SIGABRT, sig_abrt);
#endif
#ifdef SIGIOT
    signal(SIGIOT, sig_iot);
#endif
#ifdef SIGHUP
    signal(SIGHUP, sig_hup);
#endif
#ifdef SIGBUS
    signal(SIGBUS, sig_bus);
#endif
    signal(SIGSEGV, sig_segv);
    signal(SIGILL, sig_ill);
#endif        /* DEBUG */
#endif
#ifndef WIN32
#ifdef USE_BSD_SIGNALS
    signal(SIGCHLD, sig_cld);
#else
    signal(SIGCLD, sig_cld);
#endif
#endif

#ifdef HAS_CONSOLE
    if(has_console >= 0)
        signal(SIGTTIN, sig_ttin);
    signal(SIGTTOU, SIG_IGN);
#endif

    backend();
    return 0;
}
Ejemplo n.º 23
0
static int
sound_nas_play(audio_job_t aj)
{
	/* stream stuff */
	Lisp_Media_Stream *ms;
	media_substream *mss;
	/* thread stuff */
	media_thread_play_state mtp;
	/* device stuff */
	Lisp_Object device;
	Lisp_Audio_Device *lad = NULL;
	sound_nas_data_t *snd = NULL;
	/* nas stuff */
	AuElement elms[3];
	AuStatus as;
	int bsize = 0;
	/* subthread stuff */
	sound_nas_aj_data_t _snsd, *snsd = &_snsd;
	sxe_mse_volume_args _volargs, *volargs = &_volargs;
	sxe_mse_rerate_args _rrargs, *rrargs = &_rrargs;
	/* cache stuff */
	int alloced_myself = 0;

	SOUND_UNPACK_MT(aj, device, ms, mss, lad, snd, snsd->mtap);

	/* refuse to do anything if the AuServer pointer is not set */
	if (snd->aud == NULL) {
		NAS_DEBUG_C("b0rked connection, gute Nacht!\n");
		return 0;
	}

	/* install error handlers before anything else */
	AuSetErrorHandler(snd->aud, nas_error_handler);
	AuSetIOErrorHandler(snd->aud, nas_IOerror_handler);

	/* find physical output device */
	snsd->dev = nas_find_device(snd->aud, snsd->mtap->channels);

	if (snsd->dev == AuNone ||
	    !(snsd->flow = AuCreateFlow(snd->aud, NULL))) {
		/* No physical output device found or flow creation failed. */
		NAS_DEBUG_C("no physical devices for this stream\n");
		return 0;
	}

	/* A system call interrupted with a SIGALRM or SIGIO
	   comes back here */
	if (SETJMP(nas_server_sig)) {
		NAS_CRITICAL("Caught the lethal signal.\n");
		snd->aud = NULL;
		sound_nas_finish(snd);
		goto uhoh;
	}

	/* init the snsd */
	snsd->samplerate = 0;
	snsd->framesize = (snsd->channels = snsd->mtap->channels)
		* sizeof(int16_t);
	snsd->msf = MEDIA_SAMPLE_FORMAT(sxe_msf_S16);
	snsd->coe_ch_cnt = 0;
	snsd->resolution =
		(snsd->mtap->samplerate * MTPSTATE_REACT_TIME) / 1000000;
	bsize = (snsd->resolution + NAS_FRAG_SIZE - 1) & ~(NAS_FRAG_SIZE-1);

	snsd->snd = snd;
	snsd->buffer_size = bsize;
	snsd->writepos = snsd->readpos = 0;
	snsd->overfill = snsd->underrun = 0;

	/* set up flow */
	AuMakeElementImportClient(elms+0, snsd->mtap->samplerate,
				  AuFormatLinearSigned16LSB,
				  snsd->mtap->channels,
				  AuTrue,
				  bsize, bsize / 2,
				  0, NULL);
	snsd->gain = AuFixedPointFromFraction(1, 1);
	AuMakeElementMultiplyConstant(elms+1, 0, snsd->gain);
	AuMakeElementExportDevice(elms+2, 0, snsd->dev,
				  snsd->mtap->samplerate,
				  AuUnlimitedSamples, 0, NULL);
	AuSetElements(snd->aud, snsd->flow, AuTrue, 3, elms, &as);

	if (as != AuSuccess) {
		NAS_DEBUG_C("play(): AuSetElements failed\n");
		return 0;
	}

#if 0				/* atm we insist on having stereo access */
	/* the channel effect */
	ADD_MEDIA_SAMPLE_EFFECT(
		snsd->coe_chain, snsd->coe_ch_cnt,
		MEDIA_SAMPLE_EFFECT(sxe_mse_2ch_to_1ch), NULL);
#endif

	/* the volume effect */
	ADD_MEDIA_SAMPLE_EFFECT(
		snsd->coe_chain, snsd->coe_ch_cnt,
		MEDIA_SAMPLE_EFFECT(sxe_mse_volume), volargs);
	volargs->num_channels = snsd->channels;
	snsd->volargs = volargs;

	/* the rerate effect */
	ADD_MEDIA_SAMPLE_EFFECT(
		snsd->coe_chain, snsd->coe_ch_cnt,
		MEDIA_SAMPLE_EFFECT(sxe_mse_rerate), rrargs);
	rrargs->num_channels = snsd->channels;
	rrargs->srcrate = rrargs->tgtrate = 1;
	snsd->rrargs = rrargs;

	AuRegisterEventHandler(snd->aud, AuEventHandlerIDMask |
			       AuEventHandlerTypeMask,
			       AuEventTypeElementNotify, snsd->flow,
			       nas_event_handler, (AuPointer)aj);

	/* rewind the stream */
	media_stream_meth(ms, rewind)(mss);

	/* play chunks of the stream */
	SXE_MUTEX_LOCK(&aj->mtx);
	if (aj->buffer_alloc_size < SOUND_MAX_AUDIO_FRAME_SIZE) {
		alloced_myself = 1;
		aj->buffer = xmalloc_atomic(SOUND_MAX_AUDIO_FRAME_SIZE);
		aj->buffer_alloc_size = SOUND_MAX_AUDIO_FRAME_SIZE;
	}
	SXE_MUTEX_UNLOCK(&aj->mtx);
	snsd->mtp = MTPSTATE_STOP;
	snsd->volume = -1;
	audio_job_device_data(aj) = snsd;

	/* prefill the buffer */
	NAS_DEBUG_S("prefill the buffer: %d\n", 4*bsize);
	if (!nas_fill(aj, 4*bsize))
		goto uhoh;

	while (aj->play_state != MTPSTATE_STOP) {

#if 0
		if (aj->volume != snsd->volume) {
			AuElementParameters aep;
			NAS_DEBUG_S("Setting volume.\n");
			snsd->volume = aj->volume;
			snsd->gain = AU_FIXED_POINT_SCALE*(snsd->volume)/127;
			aep.parameters[AuParmsMultiplyConstantConstant] =
				snsd->gain;
			aep.flow = snd->flow;
			aep.element_num = 1;
			aep.num_parameters = AuParmsMultiplyConstant;

			AuSetElementParameters(snd->aud, 1, &aep, &as);
			if (as != AuSuccess) {
				NAS_DEBUG_S("Setting volume failed.\n");
			}
		}
#endif

#ifdef EF_USE_ASYNEQ
		/* events for me audio-job? */
		if (audio_job_queue(aj)) {
			sound_nas_handle_aj_events(aj);
		}
#endif

		SXE_MUTEX_LOCK(&aj->mtx);
		mtp = aj->play_state;
		SXE_MUTEX_UNLOCK(&aj->mtx);
		switch (mtp) {
		case MTPSTATE_RUN:
			if (snsd->mtp != mtp) {
				NAS_DEBUG("ah, gotta work again\n");
				AuStartFlow(snd->aud, snsd->flow, &as);
				if (as != AuSuccess) {
					NAS_DEBUG_C("play(): "
						    "AuStartFlow failed\n");
					aj->play_state = MTPSTATE_STOP;
				}
			}
			nas_empty_event_queue(snsd);
			usleep(snsd->resolution);
			break;
		case MTPSTATE_PAUSE:
			if (snsd->mtp != mtp) {
				NAS_DEBUG("sleeping for %d\n",
					  snsd->resolution);
				AuStopFlow(snd->aud, snsd->flow, &as);
			}
			usleep(snsd->resolution);
			break;

		case MTPSTATE_UNKNOWN:
		case MTPSTATE_STOP:
		case NUMBER_OF_MEDIA_THREAD_PLAY_STATES:
		default:
			NAS_DEBUG("ACK, quit\n");
			AuStopFlow(snd->aud, snsd->flow, &as);
			SXE_MUTEX_LOCK(&aj->mtx);
			aj->play_state = MTPSTATE_STOP;
			SXE_MUTEX_UNLOCK(&aj->mtx);
			break;
		}
		snsd->mtp = mtp;
	}

uhoh:
	/* -- Close and shutdown -- */
	SXE_MUTEX_LOCK(&aj->mtx);
	if (alloced_myself && aj->buffer) {
		xfree(aj->buffer);
	}
	aj->buffer = NULL;
	aj->buffer_alloc_size = 0;
	SXE_MUTEX_UNLOCK(&aj->mtx);

	return 1;
}
Ejemplo n.º 24
0
Archivo: ftp.c Proyecto: kumakichi/w3m
Str
loadFTPDir0(ParsedURL *pu)
#endif
{
    Str FTPDIRtmp;
    Str tmp;
    int status;
    volatile int sv_type;
    char *realpathname, *fn, *q;
    char **flist;
    int i, nfile, nfile_max;
    MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL;
#ifdef USE_M17N
    wc_ces doc_charset = DocumentCharset;

    *charset = WC_CES_US_ASCII;
#endif
    if (current_ftp.data == NULL)
        return NULL;
    tmp = ftp_command(&current_ftp, "SYST", NULL, &status);
    if (strstr(tmp->ptr, "UNIX") != NULL || !strncmp(tmp->ptr + 4, "Windows_NT", 10))	/* :-) */
        sv_type = UNIXLIKE_SERVER;
    else
        sv_type = SERVER_NONE;
    if (pu->file == NULL || *pu->file == '\0') {
        if (sv_type == UNIXLIKE_SERVER)
            ftp_command(&current_ftp, "LIST", NULL, &status);
        else
            ftp_command(&current_ftp, "NLST", NULL, &status);
        pu->file = "/";
    }
    else {
        realpathname = file_unquote(pu->file);
        if (*realpathname == '/' && *(realpathname + 1) == '~')
            realpathname++;
        if (sv_type == UNIXLIKE_SERVER) {
            ftp_command(&current_ftp, "CWD", realpathname, &status);
            if (status == 250)
                ftp_command(&current_ftp, "LIST", NULL, &status);
        }
        else
            ftp_command(&current_ftp, "NLST", realpathname, &status);
    }
    if (status != 125 && status != 150) {
        fclose(current_ftp.data);
        current_ftp.data = NULL;
        return NULL;
    }
    tmp = parsedURL2Str(pu);
    if (Strlastchar(tmp) != '/')
        Strcat_char(tmp, '/');
    fn = html_quote(tmp->ptr);
    tmp =
        convertLine(NULL, Strnew_charp(file_unquote(tmp->ptr)), RAW_MODE,
                    charset, doc_charset);
    q = html_quote(tmp->ptr);
    FTPDIRtmp = Strnew_m_charp("<html>\n<head>\n<base href=\"", fn,
                               "\">\n<title>", q,
                               "</title>\n</head>\n<body>\n<h1>Index of ", q,
                               "</h1>\n", NULL);

    if (SETJMP(AbortLoading) != 0) {
        if (sv_type == UNIXLIKE_SERVER)
            Strcat_charp(FTPDIRtmp, "</a></pre>\n");
        else
            Strcat_charp(FTPDIRtmp, "</a></ul>\n");
        Strcat_charp(FTPDIRtmp, "<p>Transfer Interrupted!\n");
        goto ftp_end;
    }
    TRAP_ON;

    if (sv_type == UNIXLIKE_SERVER)
        Strcat_charp(FTPDIRtmp, "<pre>\n");
    else
        Strcat_charp(FTPDIRtmp, "<ul>\n<li>");
    Strcat_charp(FTPDIRtmp, "<a href=\"..\">[Upper Directory]</a>\n");

    nfile_max = 100;
    flist = New_N(char *, nfile_max);
    nfile = 0;
    if (sv_type == UNIXLIKE_SERVER) {
        char *name, *link, *date, *size, *type_str;
        int ftype, max_len, len, j;

        max_len = 20;
        while (tmp = Strfgets(current_ftp.data), tmp->length > 0) {
            Strchop(tmp);
            if ((ftype =
                        ex_ftpdir_name_size_date(tmp->ptr, &name, &link, &date,
                                                 &size)) == FTPDIR_NONE)
                continue;
            if (!strcmp(".", name) || !strcmp("..", name))
                continue;
            len = strlen(name);
            if (!len)
                continue;
            if (ftype == FTPDIR_DIR) {
                len++;
                type_str = "/";
            }
            else if (ftype == FTPDIR_LINK) {
                len++;
                type_str = "@";
            }
            else {
                type_str = " ";
            }
            if (max_len < len)
                max_len = len;
            flist[nfile++] = Sprintf("%s%s\n%s  %5s%s", name, type_str, date,
                                     size, link)->ptr;
            if (nfile == nfile_max) {
                nfile_max *= 2;
                flist = New_Reuse(char *, flist, nfile_max);
            }
        }
Ejemplo n.º 25
0
Archivo: editmsg.c Proyecto: wfp5p/elm
/*
 * The editor used by edit_message() when "builtin" or "none" are selected.
 * Return 0 if successful, -1 on error.
 */
static int builtin_editor(const char *filename, SEND_HEADER *shdr)
{
    char linebuf[SLEN];		/* line input buffer			*/
    char wrapbuf[SLEN];		/* wrapped line overflow buffer		*/
    char tmpbuf[SLEN];		/* scratch buffer			*/
    FILE *fp;			/* output stream to "filename"		*/
    int rc;			/* return code from this procedure	*/
    int is_wrapped;		/* wrapped line flag			*/
    int err;			/* temp holder for errno		*/
    SIGHAND_TYPE (*oldint)();	/* previous value of SIGINT		*/
    SIGHAND_TYPE (*oldquit)();	/* previous value of SIGQUIT		*/
    SIGHAND_TYPE builtin_interrupt_handler();

    /* the built-in editor is not re-entrant! */
    assert(!builtin_active);

    /* initialize return code to failure */
    rc = -1;

    if ((fp = fopen(filename, "r+")) == NULL) {
	err = errno;
	sprintf(tmpbuf, catgets(elm_msg_cat, ElmSet, ElmCouldntOpenAppend,
	    "Couldn't open %s for update [%s]."),
	    filename, strerror(err));
	PutLine(-1, -1, tmpbuf);
	dprint(1, (debugfile,
	    "Error encountered trying to open file %s;\n", filename));
	dprint(1, (debugfile, "** %s **\n", strerror(err)));
	return rc;
    }

    /* skip past any existing text */
    fseek(fp, 0, SEEK_END);

    /* prompt user, depending upon whether file already has text */
    if (fsize(fp) > 0L)
	strcpy(tmpbuf, catgets(elm_msg_cat, ElmSet, ElmContinueEntering,
	    "\n\rContinue entering message."));
    else
	strcpy(tmpbuf, catgets(elm_msg_cat, ElmSet, ElmEnterMessage,
	    "\n\rEnter message."));
    strcat(tmpbuf, catgets(elm_msg_cat, ElmSet, ElmTypeElmCommands,
	"  Type Elm commands on lines by themselves.\n\r"));
    sprintf(tmpbuf+strlen(tmpbuf),
	catgets(elm_msg_cat, ElmSet, ElmCommandsInclude,
	"Commands include:  ^D or '.' to end, %cp to list, %c? for help.\n\r\n\r"),
	escape_char, escape_char);
    CleartoEOS();
    PutLine(-1, -1, tmpbuf);

    builtin_active = TRUE;
    builtin_interrupt_count = 0;

    oldint  = signal(SIGINT,  builtin_interrupt_handler);
    oldquit = signal(SIGQUIT, builtin_interrupt_handler);

    /* return location for interrupts */
    while (SETJMP(builtin_jmpbuf) != 0) {
	if (builtin_interrupt_count == 1) {
	    PutLine(-1, -1, catgets(elm_msg_cat, ElmSet,
		ElmEditmsgOneMoreCancel,
		"(Interrupt. One more to cancel this letter.)\n\r"));
	} else {
	    PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmEditmsgCancelled,
		"(Interrupt. Letter canceled.)\n\r"));
	    goto done;
	}
    }

    for (;;) {

	/* re-open file if it was closed out on a call to an external editor */
	if (fp == NULL) {
	    if ((fp = fopen(filename, "a+")) == NULL) {
		err = errno;
		sprintf(tmpbuf, catgets(elm_msg_cat, ElmSet,
		    ElmCouldntOpenAppend,
		    "Couldn't open %s for update [%s]."),
		    filename, strerror(err));
		PutLine(-1, -1, tmpbuf);
		dprint(1, (debugfile,
		    "Error encountered trying to open file %s;\n", filename));
		dprint(1, (debugfile, "** %s **\n", strerror(err)));
		goto done;
	    }
	    PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmPostEdContinue,
		"(Continue entering message.  Type ^D or '.' on a line by itself to end.)\n\r"));
	}

	linebuf[0] = '\0';
	wrapbuf[0] = '\0';
	is_wrapped = 0;

more_wrap:
	if (wrapped_enter(linebuf, wrapbuf, -1, -1, fp, &is_wrapped) != 0)
	    break;

	if (is_wrapped) {
	    fprintf(fp, "%s\n", linebuf);
	    NewLine();
	    (void) strcpy(linebuf, wrapbuf);
	    wrapbuf[0] = '\0';
	    goto more_wrap;
	}

	/* reset consecutive interrupt counter */
	builtin_interrupt_count = 0;

	/* a lone "." signals end of text */
	if (strcmp(linebuf, ".") == 0)
	    break;

	/* process line of text */
	if (linebuf[0] != escape_char) {
	   fprintf(fp, "%s\n", linebuf);
	   NewLine();
	   continue;
	}

	/* command character was escaped */
	if (linebuf[1] == escape_char) {
	    fprintf(fp, "%s\n", linebuf+1);
	    continue;
	}

	switch (tolower(linebuf[1])) {

	case '?':
	    tilde_help();
	    break;

	case 't':
	    get_with_expansion("\n\rTo: ",
			shdr->to, shdr->expanded_to, linebuf);
	    break;

	case 'b':
	    get_with_expansion("\n\rBcc: ",
			shdr->bcc, shdr->expanded_bcc, linebuf);
	    break;

	case 'c':
	    get_with_expansion("\n\rCc: ",
			shdr->cc, shdr->expanded_cc, linebuf);
	    break;

	case 's':
	    get_with_expansion("\n\rSubject: ",
			shdr->subject, (char *)NULL, linebuf);
	    break;

	case 'h':
	    get_with_expansion("\n\rTo: ",
			shdr->to, shdr->expanded_to, (char *)NULL);
	    get_with_expansion("Cc: ",
			shdr->cc, shdr->expanded_cc, (char *)NULL);
	    get_with_expansion("Bcc: ",
			shdr->bcc, shdr->expanded_bcc, (char *)NULL);
	    get_with_expansion("Subject: ",
			shdr->subject, (char *)NULL, (char *)NULL);
	    break;

	case 'r':
	    read_in_file(fp, linebuf+2, 1);
	    break;

	case 'e':
	    if (e_editor[0] == '\0') {
		PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmDontKnowEmacs,
		    "\n\r(Don't know where Emacs would be. Continue.)\n\r"));
		break;
	    }
	    NewLine();
	    fclose(fp);
	    fp = NULL;
	    (void) edit_message(filename, shdr, e_editor);
	    break;

	case 'v':
	    NewLine();
	    fclose(fp);
	    fp = NULL;
	    (void) edit_message(filename, shdr, v_editor);
	    break;

	case 'o':
	    PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmEnterNameEditor,
		"\n\rPlease enter the name of the editor: "));
	    if (enter_string(tmpbuf, sizeof(tmpbuf), -1, -1, ESTR_ENTER) < 0
			|| tmpbuf[0] == '\0') {
		PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmSimpleContinue,
		    "(Continue.)\n\r"));
		break;
	    }
	    NewLine();
	    fclose(fp);
	    fp = NULL;
	    (void) edit_message(filename, shdr, tmpbuf);
	    break;

	case '<':
	    NewLine();
	    if (strlen(linebuf) < 3) {
		PutLine(-1, -1, catgets(elm_msg_cat,
		    ElmSet, ElmUseSpecificCommand,
		   "(You need to use a specific command here. Continue.)\n\r"));
		break;
	    }
	    sprintf(tmpbuf, "%s%s.%d", temp_dir, temp_edit, getpid());
	    sprintf(linebuf+strlen(linebuf), " >%s 2>&1", tmpbuf);
	    (void) system_call(linebuf+2, SY_COOKED|SY_ENAB_SIGINT|SY_DUMPSTATE);
	    read_in_file(fp, tmpbuf, 0);
	    (void) unlink(tmpbuf);
	    break;

	case '!':
	    NewLine();
	    (void) system_call(
		(strlen(linebuf) < 3 ? (char *)NULL : linebuf+2),
		SY_COOKED|SY_USER_SHELL|SY_ENAB_SIGINT|SY_DUMPSTATE);
	    PutLine(LINES, 0, catgets(elm_msg_cat, ElmSet, ElmSimpleContinue,
		"(Continue.)\n\r"));
	    break;

	case 'm': /* same as 'f' but with leading prefix added */
	case 'f': /* this can be directly translated into a
			 'readmsg' call with the same params! */
	    NewLine();
	    read_in_messages(fp, linebuf+1);
	    break;

	case 'p': /* print out message so far */
	    print_message_so_far(fp, shdr);
	    break;

	default:
	    sprintf(tmpbuf, catgets(elm_msg_cat, ElmSet, ElmDontKnowChar,
		"\n\r(Don't know what %c%c is. Try %c? for help.)\n\r"),
		 escape_char, linebuf[1], escape_char);
	    PutLine(-1, -1, tmpbuf);
	    break;

	}

    }

    PutLine(-1, -1, catgets(elm_msg_cat, ElmSet, ElmEndOfMessage,
	"\n\r<end-of-message>\n\r\n\r\n\r\n\r"));
    rc = 0;

done:
    (void) signal(SIGINT,  oldint);
    (void) signal(SIGQUIT, oldquit);
    if (fp != NULL)
	fclose(fp);
    builtin_active = FALSE;
    return rc;
}
Ejemplo n.º 26
0
Str
loadNewsgroup0(ParsedURL *pu)
#endif
{
    volatile Str page;
    Str tmp;
    URLFile f;
    Buffer *buf;
    char *qgroup, *p, *q, *s, *t, *n;
    char *volatile scheme, *volatile group, *volatile list;
    int status, i, first, last;
    volatile int flag = 0, start = 0, end = 0;
    MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL;
#ifdef USE_M17N
    wc_ces doc_charset = DocumentCharset, mime_charset;

    *charset = WC_CES_US_ASCII;
#endif
    if (current_news.host == NULL || !pu->file || *pu->file == '\0')
	return NULL;
    group = allocStr(pu->file, -1);
    if (pu->scheme == SCM_NNTP_GROUP)
	scheme = "/";
    else
	scheme = "news:";
    if ((list = strchr(group, '/'))) {
	/* <newsgroup>/<start-number>-<end-number> */
	*list++ = '\0';
    }
    if (fmInitialized) {
	message(Sprintf("Reading newsgroup %s...", group)->ptr, 0, 0);
	refresh();
    }
    qgroup = html_quote(group);
    group = file_unquote(group);
    page = Strnew_m_charp("<html>\n<head>\n<base href=\"",
			  parsedURL2Str(pu)->ptr, "\">\n<title>Newsgroup: ",
			  qgroup, "</title>\n</head>\n<body>\n<h1>Newsgroup: ",
			  qgroup, "</h1>\n<hr>\n", NULL);

    if (SETJMP(AbortLoading) != 0) {
	news_close(&current_news);
	Strcat_charp(page, "</table>\n<p>Transfer Interrupted!\n");
	goto news_end;
    }
    TRAP_ON;

    tmp = news_command(&current_news, "GROUP", group, &status);
    if (status != 211)
	goto news_list;
    if (sscanf(tmp->ptr, "%d %d %d %d", &status, &i, &first, &last) != 4)
	goto news_list;
    if (list && *list) {
	if ((p = strchr(list, '-'))) {
	    *p++ = '\0';
	    end = atoi(p);
	}
	start = atoi(list);
	if (start > 0) {
	    if (start < first)
		start = first;
	    if (end <= 0)
		end = start + MaxNewsMessage - 1;
	}
    }
    if (start <= 0) {
	start = first;
	end = last;
	if (end - start > MaxNewsMessage - 1)
	    start = end - MaxNewsMessage + 1;
    }
    page = Sprintf("<html>\n<head>\n<base href=\"%s\">\n\
<title>Newsgroup: %s %d-%d</title>\n\
</head>\n<body>\n<h1>Newsgroup: %s %d-%d</h1>\n<hr>\n", parsedURL2Str(pu)->ptr, qgroup, start, end, qgroup, start, end);
    if (start > first) {
	i = start - MaxNewsMessage;
	if (i < first)
	    i = first;
	Strcat(page, Sprintf("<a href=\"%s%s/%d-%d\">[%d-%d]</a>\n", scheme,
			     qgroup, i, start - 1, i, start - 1));
    }

    Strcat_charp(page, "<table>\n");
    news_command(&current_news, "XOVER", Sprintf("%d-%d", start, end)->ptr,
		 &status);
    if (status == 224) {
	f.scheme = SCM_NEWS;
	while (true) {
	    tmp = StrISgets(current_news.rf);
	    if (NEWS_ENDLINE(tmp->ptr))
		break;
	    if (sscanf(tmp->ptr, "%d", &i) != 1)
		continue;
	    if (!(s = strchr(tmp->ptr, '\t')))
		continue;
	    s++;
	    if (!(n = strchr(s, '\t')))
		continue;
	    *n++ = '\0';
	    if (!(t = strchr(n, '\t')))
		continue;
	    *t++ = '\0';
	    if (!(p = strchr(t, '\t')))
		continue;
	    *p++ = '\0';
	    if (*p == '<')
		p++;
	    if (!(q = strchr(p, '>')) && !(q = strchr(p, '\t')))
		continue;
	    *q = '\0';
	    tmp = decodeMIME(Strnew_charp(s), &mime_charset);
	    s = convertLine(&f, tmp, HEADER_MODE,
			    mime_charset ? &mime_charset : charset,
			    mime_charset ? mime_charset : doc_charset)->ptr;
	    tmp = decodeMIME(Strnew_charp(n), &mime_charset);
	    n = convertLine(&f, tmp, HEADER_MODE,
			    mime_charset ? &mime_charset : charset,
			    mime_charset ? mime_charset : doc_charset)->ptr;
	    add_news_message(page, i, t, n, s, p, scheme,
			     pu->scheme == SCM_NNTP_GROUP ? qgroup : NULL);
	}
    }
    else {
	init_stream(&f, SCM_NEWS, current_news.rf);
	buf = newBuffer(INIT_BUFFER_WIDTH);
	for (i = start; i <= end && i <= last; i++) {
	    news_command(&current_news, "HEAD", Sprintf("%d", i)->ptr,
			 &status);
	    if (status != 221)
		continue;
	    readHeader(&f, buf, FALSE, NULL);
	    if (!(p = checkHeader(buf, "Message-ID:")))
		continue;
	    if (*p == '<')
		p++;
	    if (!(q = strchr(p, '>')) && !(q = strchr(p, '\t')))
		*q = '\0';
	    if (!(s = checkHeader(buf, "Subject:")))
		continue;
	    if (!(n = checkHeader(buf, "From:")))
		continue;
	    if (!(t = checkHeader(buf, "Date:")))
		continue;
	    add_news_message(page, i, t, n, s, p, scheme,
			     pu->scheme == SCM_NNTP_GROUP ? qgroup : NULL);
	}
    }
    Strcat_charp(page, "</table>\n");

    if (end < last) {
	i = end + MaxNewsMessage;
	if (i > last)
	    i = last;
	Strcat(page, Sprintf("<a href=\"%s%s/%d-%d\">[%d-%d]</a>\n", scheme,
			     qgroup, end + 1, i, end + 1, i));
    }
    flag = 1;

  news_list:
    tmp = Sprintf("ACTIVE %s", group);
    if (!strchr(group, '*'))
	Strcat_charp(tmp, ".*");
    news_command(&current_news, "LIST", tmp->ptr, &status);
    if (status != 215)
	goto news_end;
    while (true) {
	tmp = StrISgets(current_news.rf);
	if (NEWS_ENDLINE(tmp->ptr))
	    break;
	if (flag < 2) {
	    if (flag == 1)
		Strcat_charp(page, "<hr>\n");
	    Strcat_charp(page, "<table>\n");
	    flag = 2;
	}
	p = tmp->ptr;
	for (q = p; *q && !IS_SPACE(*q); q++) ;
	*(q++) = '\0';
	if (sscanf(q, "%d %d", &last, &first) == 2 && last >= first)
	    i = last - first + 1;
	else
	    i = 0;
	Strcat(page,
	       Sprintf
	       ("<tr><td align=right>%d<td><a href=\"%s%s\">%s</a>\n", i,
		scheme, html_quote(file_quote(p)), html_quote(p)));
    }
    if (flag == 2)
	Strcat_charp(page, "</table>\n");

  news_end:
    Strcat_charp(page, "</body>\n</html>\n");
    TRAP_OFF;
    return page;
}
Ejemplo n.º 27
0
int main P2(int, argc, char **, argv)
{
    time_t tm;
    int i, new_mudlib = 0, got_defaults = 0;
    int no_ip_demon = 0;
    char *p;
    char version_buf[80];
#if 0
    int dtablesize;
#endif
    error_context_t econ;

#if !defined(LATTICE) && !defined(OLD_ULTRIX) && !defined(sequent) && \
    !defined(sgi)
    void tzset();
#endif
    struct lpc_predef_s predefs;

#if !defined(__SASC) && (defined(AMITCP) || defined(AS225))
    amiga_sockinit();
    atexit(amiga_sockexit);
#endif
#ifdef WRAPPEDMALLOC
    wrappedmalloc_init();
#endif				/* WRAPPEDMALLOC */
#ifdef DEBUGMALLOC
    MDinit();
#endif

#if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL))
    moncontrol(0);
#endif
#if !defined(OLD_ULTRIX) && !defined(LATTICE) && !defined(sequent)
    tzset();
#endif
    boot_time = get_current_time();

    const0.type = T_NUMBER;
    const0.u.number = 0;
    const1.type = T_NUMBER;
    const1.u.number = 1;

    /* const0u used by undefinedp() */
    const0u.type = T_NUMBER;
    const0u.subtype = T_UNDEFINED;
    const0u.u.number = 0;

    /* const0n used by nullp() */
    const0n.type = T_NUMBER;
    const0n.subtype = T_NULLVALUE;
    const0n.u.number = 0;

    fake_prog.program_size = 0;

    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *) &i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10) {
	fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n");
	exit(-1);
    }

    /*
     * An added test: can we do EXTRACT_UCHAR(x++)?
     * (read_number, etc uses it)
     */
    p = (char *) &i;
    (void) EXTRACT_UCHAR(p++);
    if ((p - (char *) &i) != 1) {
	fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n");
	exit(-1);
    }

    /*
     * Check the living hash table size
     */
    if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 &&
	CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 &&
	CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) {
	fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n");
	exit(-1);
    }

#ifdef RAND
    srand(get_current_time());
#else
#  ifdef DRAND48
    srand48(get_current_time());
#  else
#    ifdef RANDOM
    srandom(get_current_time());
#    else
    fprintf(stderr, "Warning: no random number generator specified!\n");
#    endif
#  endif
#endif
    current_time = get_current_time();
    /*
     * Initialize the microsecond clock.
     */
    init_usec_clock();

    /* read in the configuration file */

    got_defaults = 0;
    for (i = 1; (i < argc) && !got_defaults; i++) {
	if (argv[i][0] != '-') {
	    set_defaults(argv[i]);
	    got_defaults = 1;
	}
    }
    if (!got_defaults) {
	fprintf(stderr, "You must specify the configuration filename as an argument.\n");
	exit(-1);
    }

    printf("Initializing internal tables....\n");
    init_strings();		/* in stralloc.c */
    init_otable();		/* in otable.c */
    init_identifiers();		/* in lex.c */
    init_locals();              /* in compiler.c */

/* disable this for now */
#if 0
    /*
     * We estimate that we will need MAX_USERS + MAX_EFUN_SOCKS + 10 file
     * descriptors if the maximum number of users were to log in and all LPC
     * sockets were in use.  This is a pretty close estimate.
     */
#ifndef LATTICE
    dtablesize = MAX_USERS + MAX_EFUN_SOCKS + 10;
#else
    /*
     * Amiga sockets separate from file descriptors
     */
    dtablesize = MAX_USERS + MAX_EFUN_SOCKS;
#endif

    /*
     * If our estimate is larger than FD_SETSIZE, then we need more file
     * descriptors than the operating system can handle.  This is a problem
     * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both.
     */
    if (dtablesize > FD_SETSIZE) {
	fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n");
	fprintf(stderr, "         Configuration exceeds system capacity by %d descriptor(s).\n",
		dtablesize - FD_SETSIZE);
    }
#ifdef HAS_SETDTABLESIZE
    /*
     * If the operating system supports setdtablesize() then we can request
     * the number of file descriptors we really need.  First check to see if
     * wee already have enough.  If so dont bother the OS. If not, attempt to
     * allocate the number we estimated above.  There are system imposed
     * limits on file descriptors, so we may not get as many as we asked for.
     * Check to make sure we get enough.
     */
    if (getdtablesize() < dtablesize)
	if (setdtablesize(dtablesize) < dtablesize) {
	    fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n");
	    fprintf(stderr, "         setdtablesize() could not allocate %d descriptor(s).\n",
		    getdtablesize() - dtablesize);
	}
    /*
     * Just be polite and tell the administrator how many he has.
     */
    fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n",
	    getdtablesize(), dtablesize);
#endif
#endif
    time_to_clean_up = TIME_TO_CLEAN_UP;
    time_to_swap = TIME_TO_SWAP;
    max_cost = MAX_COST;
    reserved_size = RESERVED_SIZE;
    max_array_size = MAX_ARRAY_SIZE;
    max_buffer_size = MAX_BUFFER_SIZE;
    max_string_length = MAX_STRING_LENGTH;
    master_file_name = (char *) MASTER_FILE;
    /* fix the filename */
    while (*master_file_name == '/') master_file_name++;
    p = master_file_name;
    while (*p++);
    if (p[-2]=='c' && p[-3]=='.')
	p[-3]=0;
    mud_lib = (char *) MUD_LIB;
    set_inc_list(INCLUDE_DIRS);
    if (reserved_size > 0)
	reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area");
    for (i = 0; i < sizeof consts / sizeof consts[0]; i++)
	consts[i] = exp(-i / 900.0);
    init_num_args();
    reset_machine(1);
    /*
     * The flags are parsed twice ! The first time, we only search for the -m
     * flag, which specifies another mudlib, and the D-flags, so that they
     * will be available when compiling master.c.
     */
    for (i = 1; i < argc; i++) {
	if (argv[i][0] != '-')
	    continue;
	switch (argv[i][1]) {
	case 'D':
	    if (argv[i][2]) {	/* Amylaar : allow flags to be passed down to
				 * the LPC preprocessor */
		struct lpc_predef_s *tmp;

		tmp = &predefs;
		tmp->flag = argv[i] + 2;
		tmp->next = lpc_predefs;
		lpc_predefs = tmp;
		continue;
	    }
	    fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]);
	    exit(-1);
	case 'N':
	    no_ip_demon++;
	    continue;
#ifdef YYDEBUG
	case 'y':
	    yydebug = 1;
	    continue;
#endif				/* YYDEBUG */
	case 'm':
	    mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir");
	    if (chdir(mud_lib) == -1) {
		fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
		exit(-1);
	    }
	    new_mudlib = 1;
	    break;
	}
    }
    if (!new_mudlib && chdir(mud_lib) == -1) {
	fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
	exit(-1);
    }
    get_version(version_buf);
    time(&tm);
    debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm));

#ifdef BINARIES
    init_binaries(argc, argv);
#endif
#ifdef LPC_TO_C
    init_lpc_to_c();
#endif
    add_predefines();

#ifndef NO_IP_DEMON
    if (!no_ip_demon && ADDR_SERVER_IP)
	init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT);
#endif				/* NO_IP_DEMON */

    eval_cost = max_cost;	/* needed for create() functions */

    save_context(&econ);
    if (SETJMP(econ.context)) {
	debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n", 
		      SIMUL_EFUN, MASTER_FILE);
	exit(-1);
    } else {
	init_simul_efun(SIMUL_EFUN);
	init_master(MASTER_FILE);
    }
    pop_context(&econ);

    for (i = 1; i < argc; i++) {
	if (argv[i][0] != '-') {
	    continue;
	} else {
	    /*
	     * Look at flags. -m and -o has already been tested.
	     */
	    switch (argv[i][1]) {
	    case 'D':
	    case 'N':
	    case 'm':
	    case 'y':
		continue;
	    case 'f':
		save_context(&econ);
		if (SETJMP(econ.context)) {
		    debug_message("Error while calling master::flag(\"%s\"), aborting ...", argv[i] + 2);
		    exit(-1);
		}
		push_constant_string(argv[i] + 2);
		(void) apply_master_ob(APPLY_FLAG, 1);
		if (MudOS_is_being_shut_down) {
		    debug_message("Shutdown by master object.\n");
		    exit(0);
		}
		pop_context(&econ);
		continue;
	    case 'e':
		e_flag++;
		continue;
	    case 'p':
		external_port[0].port = atoi(argv[i] + 2);
		continue;
            case 'd':
#ifdef DEBUG
                d_flag++;
#else
                debug_message("Driver must be compiled with DEBUG on to use -d.\n");
#endif
	    case 'c':
		comp_flag++;
		continue;
	    case 't':
		t_flag++;
		continue;
	    default:
		debug_message("Unknown flag: %s\n", argv[i]);
		exit(-1);
	    }
	}
    }
    if (MudOS_is_being_shut_down)
	exit(1);
    if (strlen(DEFAULT_FAIL_MESSAGE))
	default_fail_message = DEFAULT_FAIL_MESSAGE;
    else
	default_fail_message = "What?";
#ifdef PACKAGE_MUDLIB_STATS
    restore_stat_files();
#endif
#ifdef PACKAGE_SOCKETS
    init_sockets();		/* initialize efun sockets           */
#endif
    preload_objects(e_flag);
#ifdef SIGFPE
    signal(SIGFPE, sig_fpe);
#endif
#ifdef TRAP_CRASHES
#ifdef SIGUSR1
    signal(SIGUSR1, sig_usr1);
#endif
    signal(SIGTERM, sig_term);
    signal(SIGINT, sig_int);
#ifndef DEBUG
#if defined(SIGABRT) && !defined(LATTICE)
    signal(SIGABRT, sig_abrt);
#endif
#ifdef SIGIOT
    signal(SIGIOT, sig_iot);
#endif
#ifdef SIGHUP
    signal(SIGHUP, sig_hup);
#endif
#ifdef SIGBUS
    signal(SIGBUS, sig_bus);
#endif
#ifndef LATTICE
    signal(SIGSEGV, sig_segv);
    signal(SIGILL, sig_ill);
#endif
#endif				/* DEBUG */
#endif
    backend();
    return 0;
}
Ejemplo n.º 28
0
int SC_exec_async(const char *shell, char **cmnds, char **dirs,
		  const char *consh, char **conenv, int nc,
		  const char *lname, const char *fname,
		  int na, int show, int ignore, int lg)
   {int is, id, nd, ns, ja, st, sig;
    int nhst, reset, ioi;
    char *ldir[1];
    fspec *filter;
    conpool *cp;
    asyncstate *as;
    SC_contextdes hnd;

    as = CMAKE(asyncstate);
    SC_MEM_INIT(asyncstate, as);

    _SC_setup_async_state(as,
			  SC_get_host_length_max(NULL, TRUE, FALSE));
    as->debug = FALSE;

    if (lname != NULL)
       {as->log = io_open(lname, "a");
	SC_setbuf(as->log, NULL);}
    else
       as->log = NULL;

/* save old interrupt state */
    hnd = SC_which_signal_handler(SC_SIGIO);
    ioi = SC_set_io_interrupts(FALSE);
    SC_signal_n(SC_SIGIO, SIG_IGN, NULL, 0);

    filter = _SC_read_filter(fname);
    shell  = SC_get_shell(shell);

/* count commands */
    SC_ptr_arr_len(ns, cmnds);

/* count the directories */
    if (dirs == NULL)
       {ldir[0] = SC_getcwd();
	dirs    = ldir;
	nd      = 1;}
    else
       SC_ptr_arr_len(nd, dirs);

/* open the connection pool */
    nhst = SC_get_nhosts(PSY_Arch);
    nc   = min(nc, nhst);
    nc   = min(nc, ns);
    cp   = SC_open_connection_pool(nc, PSY_Arch, consh, conenv,
				   na, show, ignore,
				   DEFAULT_HEARTBEAT, filter);

    cp->as   = as;
    as->pool = cp;

    sig = SETJMP(cp->cpu);
    if (sig == 0)
       {cp->active = TRUE;

/* launch all commands */
	reset = TRUE;
        for (id = 0; id < nd; id++)
	    for (is = 0; is < ns; is++)
	        {if (IS_BARRIER(cmnds[is]))
		    {while (SC_wait_pool_job(cp, DEFAULT_WAIT) != 2);
		     reset = TRUE;}
		 
		 else
		    {ja = SC_launch_pool_job(cp, na, reset, shell,
					     dirs[id], cmnds[is]);
		     if (ja < 0)
		        {LONGJMP(cp->cpu, SC_EXIT_BAD);};

		     reset = FALSE;};};

/* wait for commands to complete */
	while (SC_wait_pool_job(cp, DEFAULT_WAIT) != 2);};

    cp->active = FALSE;
    as->pool   = NULL;

    st = SC_connection_pool_status(cp);

    if (lg == TRUE)
       {SC_close_connection_pool(cp, -1, TRUE);
	as->to_stdout = FALSE;}
    else
       {as->to_stdout = FALSE;
	SC_close_connection_pool(cp, sig, TRUE);};

    CFREE(as);

/* cleanup */
    _SC_free_filter(filter);

/* restore old interrupt state */
    SC_set_io_interrupts(ioi);
    SC_restore_signal_n(SC_SIGIO, hnd);

    if (sig == SC_EXIT_BAD)
       st = sig;

    return(st);}
Ejemplo n.º 29
0
int
main(int argc_orig, char **argv)
#endif
{
    int i;

    /* We want the current value of argc to persist across a LONGJMP from int_error().
     * Without this the compiler may put it on the stack, which LONGJMP clobbers.
     * Here we try make it a volatile variable that optimization will not affect.
     * Why do we not have to do the same for argv?   I don't know.
     * But the test cases that broke with generic argc seem fine with generic argv.
     */
    static volatile int argc;
    argc = argc_orig;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    if (setuid(getuid()) != 0) {
	fprintf(stderr,"gnuplot: refusing to run at elevated privilege\n");
	exit(EXIT_FAILURE);
    }
#endif

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    {
	int rc;
#ifdef OS2_IPC
	char semInputReadyName[40];

	sprintf(semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid());
	rc = DosCreateEventSem(semInputReadyName, &semInputReady, 0, 0);
	if (rc != 0)
	    fputs("DosCreateEventSem error\n", stderr);
#endif
	rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
    }
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif


/* init progpath and get helpfile from executable directory */
#if defined(MSDOS) || defined(OS2)
    {
	char *s;

#ifdef __EMX__
	_execname(progpath, sizeof(progpath));
#else
	safe_strncpy(progpath, argv[0], sizeof(progpath));
#endif
	/* convert '/' to '\\' */
	for (s = progpath; *s != NUL; s++)
	    if (*s == DIRSEP2)
		*s = DIRSEP1;
	/* cut program name */
	s = strrchr(progpath, DIRSEP1);
	if (s != NULL)
	    s++;
	else
	    s = progpath;
	*s = NUL;
	/* init HelpFile */
	strcpy(HelpFile, progpath);
	strcat(HelpFile, "gnuplot.gih");
	/* remove trailing "bin/" from progpath */
	if ((s != NULL) && (s - progpath >= 4)) {
	    s -= 4;
	    if (strncasecmp(s, "bin", 3) == 0)
		*s = NUL;
	}
    }
#endif /* DJGPP */

#if (defined(PIPE_IPC) || defined(_WIN32)) && (defined(HAVE_LIBREADLINE) || (defined(HAVE_LIBEDITLINE) && defined(X11)))
    /* Editline needs this to be set before the very first call to readline(). */
    /* Support for rl_getc_function is broken for utf-8 in editline. Since it is only
       really required for X11, disable this section when building without X11. */
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc'
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#if defined(HAVE_LIBREADLINE)
    using_history();
#else
    history_init();
#endif
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION] ... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -s  --slow\n"
		    "  -d  --default-settings\n"
		    "  -c  scriptfile ARG1 ARG2 ... \n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
#ifdef DEVELOPMENT_VERSION
	    printf(
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    bug_email);
#endif
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")
#ifdef _WIN32
		|| !stricmp(argv[i], "-noend") || !stricmp(argv[i], "/noend")
#endif
		) {
	    persist_cl = TRUE;
	} else if (!strncmp(argv[i], "-slow", 2) || !strcmp(argv[i], "--slow")) {
	    slow_font_startup = TRUE;
	} else if (!strncmp(argv[i], "-d", 2) || !strcmp(argv[i], "--default-settings")) {
	    /* Skip local customization read from ~/.gnuplot */
	    skip_gnuplotrc = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* This was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

    /* Switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * Do any non-X platforms suffer from this problem?
     * EAM - Jan 2013 YES.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    /* "pi" is hard-wired as the first variable */
    (void) add_udv_by_name("GNUTERM");
    (void) add_udv_by_name("NaN");
    init_constants();
    udv_user_head = &(udv_NaN->next_udv);

    init_memory();

    interactive = FALSE;

    /* April 2017:  We used to call init_terminal() here, but now   */
    /* We defer initialization until error handling has been set up. */

# if defined(_WIN32) && !defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    /* Note: we want to know whether this is an interactive session so that we can
     * decide whether or not to write status information to stderr.  The old test
     * for this was to see if (argc > 1) but the addition of optional command line
     * switches broke this.  What we really wanted to know was whether any of the
     * command line arguments are file names or an explicit in-line "-e command".
     */
    for (i = 1; i < argc; i++) {
# ifdef _WIN32
	if (!stricmp(argv[i], "/noend"))
	    continue;
# endif
	if ((argv[i][0] != '-') || (argv[i][1] == 'e') || (argv[i][1] == 'c') ) {
	    interactive = FALSE;
	    break;
	}
    }

    /* Need this before show_version is called for the first time */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    {
    unsigned int ierror;
    if (ierror = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(ierror);
    if (ierror = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(ierror);
    }
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	get_user_env();
	init_loadpath();
	init_locale();

	memset(&sm_palette, 0, sizeof(sm_palette));
	init_fit();		/* Initialization of fitting module */
#ifdef READLINE
	/* When using the built-in readline, we set the initial
	   encoding according to the locale as this is required
	   to properly handle keyboard input. */
	init_encoding();
#endif
	init_gadgets();

	/* April 2017: Now that error handling is in place, it is safe parse
	 * GNUTERM during terminal initialization.
	 * atexit processing is done in reverse order. We want
	 * the generic terminal shutdown in term_reset to be executed before
	 * any terminal specific cleanup requested by individual terminals.
	 */
	init_terminal();
	push_terminal(0);	/* remember the initial terminal */
	gp_atexit(term_reset);

	/* Execute commands in ~/.gnuplot */
	init_session();

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && !defined(_WIN32)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    read_history(expanded_history_filename);

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     */
	    gp_atexit(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

#if defined(READLINE) && defined(WGP_CONSOLE)
	    fprintf(stderr, "Encoding set to '%s'.\n", encoding_names[encoding]);
#endif
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (!successful_initialization) {
	    /* Only print the warning once */
	    successful_initialization = TRUE;
	    fprintf(stderr,"WARNING: Error during initialization\n\n");
	}
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else {
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */

	/* Why a goto?  Because we exited the loop below via int_error */
	/* using LONGJMP.  The compiler was not expecting this, and    */
	/* "optimized" the handling of argc and argv such that simply  */
	/* entering the loop again from the top finds them messed up.  */
	/* If we reenter the loop via a goto then there is some hope   */
	/* that code reordering does not hurt us.                      */
	if (reading_from_dash && interactive)
	    goto RECOVER_FROM_ERROR_IN_DASH;
	reading_from_dash = FALSE;

	if (!interactive && !noinputfiles) {
	    term_reset();
	    gp_exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    /* load filenames given as arguments */
    while (--argc > 0) {
	    ++argv;
	    c_token = 0;
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")
#ifdef _WIN32
		|| !stricmp(*argv, "-noend") || !stricmp(*argv, "/noend")
#endif
	    ) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));
	    } else if (strcmp(*argv, "-") == 0) {
#if defined(_WIN32) && !defined(WGP_CONSOLE)
		TextShow(&textwin);
		interactive = TRUE;
#else
		interactive = isatty(fileno(stdin));
#endif

RECOVER_FROM_ERROR_IN_DASH:
		reading_from_dash = TRUE;
		while (!com_line());
		reading_from_dash = FALSE;
		interactive = FALSE;
		noinputfiles = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		int save_state = interactive;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		interactive = FALSE;
		noinputfiles = FALSE;
		do_string(*argv);
		interactive = save_state;

	    } else if (!strncmp(*argv, "-slow", 2) || !strcmp(*argv, "--slow")) {
		slow_font_startup = TRUE;

	    } else if (!strncmp(*argv, "-d", 2) || !strcmp(*argv, "--default-settings")) {
		/* Ignore this; it already had its effect */
		FPRINTF((stderr, "ignoring -d\n"));

	    } else if (strcmp(*argv, "-c") == 0) {
		/* Pass command line arguments to the gnuplot script in the next
		 * argument. This consumes the remainder of the command line
		 */
		interactive = FALSE;
		noinputfiles = FALSE;
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -c scriptname args\n");
		    gp_exit(EXIT_FAILURE);
		}
		call_argc = GPMIN(9, argc - 1);
		for (i=0; i<=call_argc; i++) {
		    /* Need to stash argv[i] somewhere visible to load_file() */
		    call_args[i] = gp_strdup(argv[i+1]);
		}

		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 5);
		gp_exit(EXIT_SUCCESS);

	    } else if (*argv[0] == '-') {
		fprintf(stderr, "unrecognized option %s\n", *argv);
	    } else {
		interactive = FALSE;
		noinputfiles = FALSE;
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), 4);
	    }
    }

    /* take commands from stdin */
    if (noinputfiles) {
	while (!com_line())
	    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
    }

#ifdef _WIN32
    /* On Windows, handle 'persist' by keeping the main input loop running (windows/wxt), */
    /* but only if there are any windows open. Note that qt handles this properly. */
    if (persist_cl) {
	if (WinAnyWindowOpen()) {
#ifdef WGP_CONSOLE
	    if (!interactive) {
		/* no further input from pipe */
		while (WinAnyWindowOpen())
		win_sleep(100);
	    } else
#endif
	    {
		interactive = TRUE;
		while (!com_line())
		    ctrlc_flag = FALSE; /* reset asynchronous Ctrl-C flag */
		interactive = FALSE;
	    }
	}
    }
#endif

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
#if ! defined(_WIN32)
    /* Windows does the cleanup later */
    gp_exit_cleanup();
#endif
    return exit_status;
}
Ejemplo n.º 30
0
/* browser(text = "", condition = NULL, expr = TRUE, skipCalls = 0L)
 * ------- but also called from ./eval.c */
SEXP attribute_hidden do_browser(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    RCNTXT *saveToplevelContext;
    RCNTXT *saveGlobalContext;
    RCNTXT thiscontext, returncontext, *cptr;
    int savestack, browselevel;
    SEXP ap, topExp, argList;

    /* argument matching */
    PROTECT(ap = list4(R_NilValue, R_NilValue, R_NilValue, R_NilValue));
    SET_TAG(ap,  install("text"));
    SET_TAG(CDR(ap), install("condition"));
    SET_TAG(CDDR(ap), install("expr"));
    SET_TAG(CDDDR(ap), install("skipCalls"));
    argList = matchArgs(ap, args, call);
    UNPROTECT(1);
    PROTECT(argList);
    /* substitute defaults */
    if(CAR(argList) == R_MissingArg)
	SETCAR(argList, mkString(""));
    if(CADR(argList) == R_MissingArg)
	SETCAR(CDR(argList), R_NilValue);
    if(CADDR(argList) == R_MissingArg) 
	SETCAR(CDDR(argList), ScalarLogical(1));
    if(CADDDR(argList) == R_MissingArg) 
	SETCAR(CDDDR(argList), ScalarInteger(0));

    /* return if 'expr' is not TRUE */
    if( !asLogical(CADDR(argList)) ) {
        UNPROTECT(1);
        return R_NilValue;
    }

    /* Save the evaluator state information */
    /* so that it can be restored on exit. */

    browselevel = countContexts(CTXT_BROWSER, 1);
    savestack = R_PPStackTop;
    PROTECT(topExp = R_CurrentExpr);
    saveToplevelContext = R_ToplevelContext;
    saveGlobalContext = R_GlobalContext;

    if (!RDEBUG(rho)) {
        int skipCalls = asInteger(CADDDR(argList));
	cptr = R_GlobalContext;
	while ( ( !(cptr->callflag & CTXT_FUNCTION) || skipCalls--) 
		&& cptr->callflag )
	    cptr = cptr->nextcontext;
	Rprintf("Called from: ");
	int tmp = asInteger(GetOption(install("deparse.max.lines"), R_BaseEnv));
	if(tmp != NA_INTEGER && tmp > 0) R_BrowseLines = tmp;
        if( cptr != R_ToplevelContext ) {
	    PrintValueRec(cptr->call, rho);
	    SET_RDEBUG(cptr->cloenv, 1);
        } else
            Rprintf("top level \n");

	R_BrowseLines = 0;
    }

    R_ReturnedValue = R_NilValue;

    /* Here we establish two contexts.  The first */
    /* of these provides a target for return */
    /* statements which a user might type at the */
    /* browser prompt.  The (optional) second one */
    /* acts as a target for error returns. */

    begincontext(&returncontext, CTXT_BROWSER, call, rho,
		 R_BaseEnv, argList, R_NilValue);
    if (!SETJMP(returncontext.cjmpbuf)) {
	begincontext(&thiscontext, CTXT_RESTART, R_NilValue, rho,
		     R_BaseEnv, R_NilValue, R_NilValue);
	if (SETJMP(thiscontext.cjmpbuf)) {
	    SET_RESTART_BIT_ON(thiscontext.callflag);
	    R_ReturnedValue = R_NilValue;
	    R_Visible = FALSE;
	}
	R_GlobalContext = &thiscontext;
	R_InsertRestartHandlers(&thiscontext, TRUE);
	R_ReplConsole(rho, savestack, browselevel+1);
	endcontext(&thiscontext);
    }
    endcontext(&returncontext);

    /* Reset the interpreter state. */

    R_CurrentExpr = topExp;
    UNPROTECT(1);
    R_PPStackTop = savestack;
    UNPROTECT(1);
    R_CurrentExpr = topExp;
    R_ToplevelContext = saveToplevelContext;
    R_GlobalContext = saveGlobalContext;
    return R_ReturnedValue;
}