static int start_monitoring(struct devfreq *df)
{
	int ret, mbyte;

	ret = request_threaded_irq(l2pm_irq, NULL, mon_intr_handler,
			  IRQF_ONESHOT | IRQF_SHARED,
			  "cpubw_hwmon", df);
	if (ret) {
		pr_err("Unable to register interrupt handler\n");
		return ret;
	}

	mon_init();
	mon_disable(RD_MON);
	mon_disable(WR_MON);

	mbyte = (df->previous_freq * io_percent) / (2 * 100);
	prev_r_start_val = mon_set_limit_mbyte(RD_MON, mbyte);
	prev_w_start_val = mon_set_limit_mbyte(WR_MON, mbyte);
	prev_ts = ktime_get();
	prev_ab = 0;

	mon_irq_enable(RD_MON, true);
	mon_irq_enable(WR_MON, true);
	mon_enable(RD_MON);
	mon_enable(WR_MON);
	global_mon_enable(true);

	return 0;
}
Beispiel #2
0
void mpoly_randtest(mpoly_t rop, flint_rand_t state, long d, long N, 
                    const ctx_t ctx)
{
    long i, n = rop->n;

    mpoly_zero(rop, ctx);

    for (i = 0; i < N; i++)
    {
        int ins;
        mon_t m1, m2;
        char *c1;
        void *c2;

        mon_init(m1);
        mon_randtest(m1, state, n, d);

        c1 = malloc(ctx->size);
        ctx->init(ctx, c1);
        ctx->randtest_not_zero(ctx, c1, state);

        ins = RBTREE_INSERT(mpoly, &m2, &c2, rop->dict, m1, c1, &mon_cmp);

        if (ins)
        {
            mon_clear(m2);
            ctx->clear(ctx, c2);
            free(c2);
        }
    }
}
Beispiel #3
0
/******************************************************************************
 **函数名称: main 
 **功    能: 监控主程序
 **输入参数: NONE
 **输出参数: NONE
 **返    回: 0:成功 !0:失败
 **实现描述: 
 **     1. 初始化菜单环境
 **     2. 加载子菜单
 **     3. 启动菜单功能
 **注意事项: 
 **作    者: # Qifeng.zou # 2014.12.27 #
 ******************************************************************************/
int main(int argc, char *argv[])
{
    mon_opt_t opt;
    mon_cntx_t *ctx;

    memset(&opt, 0, sizeof(opt));

    umask(0);
    mem_ref_init();
    set_fd_limit(65535);
    signal(SIGPIPE, SIG_IGN);

    /* > 解析输入参数 */
    if (mon_getopt(argc, argv, &opt)) {
        return mon_usage(argv[0]);
    }

    /* > 初始化全局信息 */
    ctx = mon_init(opt.conf_path);
    if (NULL == ctx) {
        fprintf(stderr, "Initialize monitor failed!\n");
        return -1;
    }

    /* > 启动菜单模块 */
    if (menu_run(ctx->menu)) {
        fprintf(stderr, "Startup menu failed!\n");
        return -1;
    }

    return 0;
}
/* Returns MBps of read/writes for the sampling window. */
static int mon_get_mbps(int n, u32 start_val, unsigned int us)
{
	u32 overflow, count;
	long long beats;

	count = get_l2_indirect_reg(L2PMnEVCNTR(n));
	overflow = get_l2_indirect_reg(L2PMOVSR);

	if (overflow & BIT(n))
		beats = 0xFFFFFFFF - start_val + count;
	else
		beats = count - start_val;

	beats *= USEC_PER_SEC;
	beats *= bytes_per_beat;
	do_div(beats, us);
	beats = DIV_ROUND_UP_ULL(beats, MBYTE);

	pr_debug("EV%d ov: %x, cnt: %x\n", n, overflow, count);

	return beats;
}

static void do_bw_sample(struct work_struct *work);
static DECLARE_DEFERRED_WORK(bw_sample, do_bw_sample);
static struct workqueue_struct *bw_sample_wq;

static DEFINE_MUTEX(bw_lock);
static ktime_t prev_ts;
static u32 prev_r_start_val;
static u32 prev_w_start_val;

static struct msm_bus_paths bw_levels[] = {
	BW(0), BW(200),
};
static struct msm_bus_scale_pdata bw_data = {
	.usecase = bw_levels,
	.num_usecases = ARRAY_SIZE(bw_levels),
	.name = "cpubw-krait",
	.active_only = 1,
};
static u32 bus_client;
static void compute_bw(int mbps);
static irqreturn_t mon_intr_handler(int irq, void *dev_id);

#define START_LIMIT	100 /* MBps */
static int start_monitoring(void)
{
	int mb_limit;
	int ret;

	bw_sample_wq = alloc_workqueue("cpubw-krait", WQ_HIGHPRI, 0);
	if (!bw_sample_wq) {
		pr_err("Unable to alloc workqueue\n");
		return -ENOMEM;
	}

	ret = request_threaded_irq(MON_INT, NULL, mon_intr_handler,
			  IRQF_ONESHOT | IRQF_SHARED | IRQF_TRIGGER_RISING,
			  "cpubw_krait", mon_intr_handler);
	if (ret) {
		pr_err("Unable to register interrupt handler\n");
		return ret;
	}

	bus_client = msm_bus_scale_register_client(&bw_data);
	if (!bus_client) {
		pr_err("Unable to register bus client\n");
		ret = -ENODEV;
		goto bus_reg_fail;
	}

	compute_bw(START_LIMIT);

	mon_init();
	mon_disable(0);
	mon_disable(1);

	mb_limit = mult_frac(START_LIMIT, sample_ms, MSEC_PER_SEC);
	mb_limit /= 2;

	prev_r_start_val = mon_set_limit_mbyte(0, mb_limit);
	prev_w_start_val = mon_set_limit_mbyte(1, mb_limit);

	prev_ts = ktime_get();

	set_l2_indirect_reg(L2PMINTENSET, BIT(0));
	set_l2_indirect_reg(L2PMINTENSET, BIT(1));
	mon_enable(0);
	mon_enable(1);
	global_mon_enable(true);

	queue_delayed_work(bw_sample_wq, &bw_sample,
				msecs_to_jiffies(sample_ms));

	return 0;

bus_reg_fail:
	destroy_workqueue(bw_sample_wq);
	disable_irq(MON_INT);
	free_irq(MON_INT, mon_intr_handler);
	return ret;
}
Beispiel #5
0
int main(void)
{
    CLKPR = (1<<7);
    CLKPR = 0;

    /* Disable watchdog timer */
    MCUSR = 0;
    wdt_disable();

    /* Start the multi-threading kernel */
    init_kernel(STACK_MAIN);

    /* Timer */
    TCCR2B = 0x03;                   /* Pre-scaler for timer0 */
    TCCR2A = 1<<WGM21;               /* CTC mode */
    TIMSK2 = 1<<OCIE2A;              /* Interrupt on compare match */
    OCR2A  = (SCALED_F_CPU / 32 / 2400) - 1;

    TRACE_INIT;
    sei();
    t_stackErrorHandler(stackOverflow);
    fbuf_errorHandler(bufferOverflow);
    reset_params();

    /* HDLC and AFSK setup */
    mon_init(&cdc_outstr);
    adf7021_init();
    inframes  = hdlc_init_decoder( afsk_init_decoder() );
    outframes = hdlc_init_encoder( afsk_init_encoder() );
    digipeater_init();
    /* Activate digipeater in ui thread */

    /* USB */
    usb_init();
    THREAD_START(usbSerListener, STACK_USBLISTENER);

    ui_init();

    /* GPS and tracking */
    gps_init(&cdc_outstr);
    tracker_init();


    TRACE(1);
    while(1)
    {
        lbeep();
        if (t_is_idle()) {
            /* Enter idle mode or sleep mode here */
            powerdown_handler();
            sleep_mode();
        }
        else
            t_yield();
    }
}
Beispiel #6
0
/*
    Returns the monomial in $n$ variables given by the string
    \code{str}, where the string is simply a space-separated
    list of exponents.
 */
static mon_t mpoly_mon_set_str(const char * str, int n)
{
    mon_t rop;
    int i;
    size_t off;

    mon_init(rop);
    off = 0;
    for (i = 0; i < n; i++)
    {
        exp_t e = atoi(str + off);
        mon_set_exp(rop, i, e);
        off += 1 + (e >= 0) + (e >= 10) + (e >= 100);
    }

    return rop;
}
psim_init(psim *system)
{
    int cpu_nr;

    /* scrub the monitor */
    mon_init(system->monitor, system->nr_cpus);

    /* trash any pending events */
    event_queue_init(system->events);

    /* if needed, schedule a halt event.  FIXME - In the future this
       will be replaced by a more generic change to psim_command().  A
       new command `schedule NNN halt' being added. */
    if (tree_find_property(system->devices, "/openprom/options/max-iterations")) {
        event_queue_schedule(system->events,
                             tree_find_integer_property(system->devices,
                                     "/openprom/options/max-iterations") - 2,
                             psim_max_iterations_exceeded,
                             system);
    }

    /* scrub all the cpus */
    for (cpu_nr = 0; cpu_nr < system->nr_cpus; cpu_nr++)
        cpu_init(system->processors[cpu_nr]);

    /* init all the devices (which updates the cpus) */
    tree_init(system->devices, system);

    /* and the emulation (which needs an initialized device tree) */
    os_emul_init(system->os_emulation, system->nr_cpus);

    /* now sync each cpu against the initialized state of its registers */
    for (cpu_nr = 0; cpu_nr < system->nr_cpus; cpu_nr++) {
        cpu *processor = system->processors[cpu_nr];
        cpu_synchronize_context(processor, cpu_get_program_counter(processor));
        cpu_page_tlb_invalidate_all(processor);
    }

    /* force loop to start with first cpu */
    system->last_cpu = -1;
}
Beispiel #8
0
int
main(void)
{
    int i, result;
    flint_rand_t state;
    ctx_t ctx;

    printf("add_coeff... ");
    fflush(stdout);

    _randinit(state);

    ctx_init_mpq(ctx);

    for (i = 0; i < 1000; i++)
    {
        mpoly_t a;
        long n, d, N;
        mon_t m;
        char *x, *y, *z;

        n = n_randint(state, MON_MAX_VARS) + 1;
        d = n_randint(state, 50) + 1;
        N = n_randint(state, 50) + 1;

        mon_init(m);
        mon_randtest(m, state, n, d);
        x = malloc(ctx->size);
        y = malloc(ctx->size);
        z = malloc(ctx->size);
        ctx->init(ctx, x);
        ctx->init(ctx, y);
        ctx->init(ctx, z);
        ctx->randtest(ctx, x, state);

        mpoly_init(a, n, ctx);
        mpoly_randtest(a, state, d, N, ctx);

        mpoly_get_coeff(y, a, m, ctx);
        ctx->add(ctx, y, y, x);

        mpoly_add_coeff(a, m, x, ctx);
        mpoly_get_coeff(z, a, m, ctx);

        result = (ctx->equal(ctx, y, z));
        if (!result)
        {
            printf("FAIL:\n");
            mpoly_print(a, ctx); printf("\n");
            ctx->print(ctx, x); printf("\n");
            ctx->print(ctx, y); printf("\n");
            ctx->print(ctx, z); printf("\n");
            abort();
        }

        mpoly_clear(a, ctx);
        mon_clear(m);
        ctx->clear(ctx, x);
        ctx->clear(ctx, y);
        ctx->clear(ctx, z);
        free(x);
        free(y);
        free(z);
    }

    _randclear(state);
    _fmpz_cleanup();
    printf("PASS\n");
    return EXIT_SUCCESS;
}
Beispiel #9
0
int main (int argc, char *argv[])
{
	int       i;
	int       run;
	char      *cfg;
	ini_sct_t *sct;

	if (argc == 2) {
		if (str_isarg1 (argv[1], "--help")) {
			prt_help();
			return (0);
		}
		else if (str_isarg1 (argv[1], "--version")) {
			prt_version();
			return (0);
		}
	}

	cfg = NULL;
	run = 0;

	pce_log_init();
	pce_log_add_fp (stderr, 0, MSG_INF);

	par_cfg = ini_sct_new (NULL);

	if (par_cfg == NULL) {
		return (1);
	}

	i = 1;
	while (i < argc) {
		if (str_isarg2 (argv[i], "-v", "--verbose")) {
			pce_log_set_level (stderr, MSG_DEB);
		}
		else if (str_isarg2 (argv[i], "-q", "--quiet")) {
			pce_log_set_level (stderr, MSG_ERR);
		}
		else if (str_isarg2 (argv[i], "-c", "--config")) {
			i += 1;
			if (i >= argc) {
				return (1);
			}
			cfg = argv[i];
		}
		else if (str_isarg2 (argv[i], "-l", "--log")) {
			i += 1;
			if (i >= argc) {
				return (1);
			}
			pce_log_add_fname (argv[i], MSG_DEB);
		}
		else if (str_isarg2 (argv[i], "-r", "--run")) {
			run = 1;
		}
		else {
			printf ("%s: unknown option (%s)\n", argv[0], argv[i]);
			return (1);
		}

		i += 1;
	}

	pce_log (MSG_INF,
		"pce sim6502 version " PCE_VERSION_STR "\n"
		"Copyright (C) 1995-2012 Hampa Hug <*****@*****.**>\n"
	);

	if (pce_load_config (par_cfg, cfg)) {
		return (1);
	}

	sct = ini_next_sct (par_cfg, NULL, "sim6502");

	if (sct == NULL) {
		pce_log (MSG_ERR, "*** section 'sim6502' not found in config file\n");
		return (1);
	}

	par_sim = s6502_new (sct);

	e6502_set_hook_undef_fct (par_sim->cpu, par_sim, s6502_hook_undef);

	signal (SIGINT, &sig_int);
	signal (SIGSEGV, &sig_segv);

#ifdef SIGPIPE
	signal (SIGPIPE, SIG_IGN);
#endif

	pce_console_init (stdin, stdout);

	mon_init (&par_mon);
	mon_set_cmd_fct (&par_mon, s6502_do_cmd, par_sim);
	mon_set_msg_fct (&par_mon, NULL, par_sim);
	mon_set_get_mem_fct (&par_mon, par_sim->mem, mem_get_uint8);
	mon_set_set_mem_fct (&par_mon, par_sim->mem, mem_set_uint8);
	mon_set_memory_mode (&par_mon, 0);

	cmd_init (par_sim, cmd_get_sym, cmd_set_sym);

	mon_cmd_add (&par_mon, par_cmd, sizeof (par_cmd) / sizeof (par_cmd[0]));
	mon_cmd_add_bp (&par_mon);

	s6502_reset (par_sim);

	if (run) {
		s6502_run (par_sim);
		if (par_sim->brk != PCE_BRK_ABORT) {
			fputs ("\n", stdout);
		}
	}
	else {
		pce_log (MSG_INF, "type 'h' for help\n");
	}

	if (par_sim->brk != PCE_BRK_ABORT) {
		mon_run (&par_mon);
	}

	s6502_del (par_sim);

	mon_free (&par_mon);
	pce_console_done();
	pce_log_done();

	return (0);
}
Beispiel #10
0
int mpoly_set_str(mpoly_t rop, const char * str, const ctx_t ctx)
{
    int i, j, n, num;
    const size_t len = strlen(str);

    /* Step 1.  Set the number of variables */

    n = atoi(str);

    mpoly_clear(rop, ctx);
    mpoly_init(rop, n, ctx);

    /* Step 2.  Count the number of terms */

    num = 1;
    for (i = 0; i < len; i++)
    {
        if (num > 0 && str[i] == '[')
            num = -num - 1;
        else if (num < 0 && str[i] == ']')
            num = -num;
    }
    num = num - 1;

    if (num < 0)
    {
        printf("ERROR (mpoly_set_str).  num = %d\n", num);
        abort();
    }
    if (num == 0)
        return 1;

    /* Step 3.  Process the terms one after the other */

    /* Read past the first integer, and skip following white space */
    j = 0;
    while (str[j] != ' ')
        j++;
    while (str[j] == ' ')
        j++;

    for (i = 0; i < num; i++)
    {
        char *s;
        int ins, jclose;
        mon_t m, m2;
        char *c;
        void *c2;

        /*
           First we set the coefficient and the monomial separately, moving
           the index j just one past the closing bracket ']' of the monomial.
         */

        mon_init(m);
        c = malloc(ctx->size);
        ctx->init(ctx, c);

        while (str[j] != '(' && str[j] != '[')
            j++;

        if (str[j] == '(')
        {
            jclose = mpoly_str_find_close(str, j, '(', ')');
            s = mpoly_str_substr(str, j + 1, jclose);
            ctx->set_str(ctx, c, s);
            free(s);

            j = jclose + 1;
            while (str[j] != '[')
                j++;
        }
        else
        {
            ctx->one(ctx, c);
        }

        jclose = mpoly_str_find_close(str, j, '[', ']');
        s = mpoly_str_substr(str, j + 1, jclose);
        m = mpoly_mon_set_str(s, n);
        free(s);

        j = jclose + 1;

        /* Now we insert the new node */

        ins = RBTREE_INSERT(mpoly, &m2, &c2, rop->dict, m, c, &mon_cmp);

        if (ins)
        {
            printf("ERROR (mpoly_set_str).  Duplicate monomial.\n");
            abort();
        }
    }
    return 1;
}
Beispiel #11
0
void main_init(int argc, char *argv[])
{
   bool override_hw = false;
   if (argc > 1)
   {
      if (strcmp(argv[1], "calibrate") == 0)
         calibrate = true;
      else
         override_hw = true;
   }

   /* init data structures: */
   memset(&pos_in, 0, sizeof(pos_in_t));
   vec3_init(&pos_in.acc);

   /* init SCL subsystem: */
   syslog(LOG_INFO, "initializing signaling and communication link (SCL)");
   if (scl_init("pilot") != 0)
   {
      syslog(LOG_CRIT, "could not init scl module");
      die();
   }
   
   /* init params subsystem: */
   syslog(LOG_INFO, "initializing opcd interface");
   opcd_params_init("pilot.", 1);
   
   /* initialize logger: */
   syslog(LOG_INFO, "opening logger");
   if (logger_open() != 0)
   {
      syslog(LOG_CRIT, "could not open logger");
      die();
   }
   syslog(LOG_CRIT, "logger opened");
   
   LOG(LL_INFO, "initializing platform");
   if (arcade_quad_init(&platform, override_hw) < 0)
   {
      LOG(LL_ERROR, "could not initialize platform");
      die();
   }
   acc_mag_cal_init();
   cmc_init();
 
   const size_t array_len = sizeof(float) * platform.n_motors;
   setpoints = malloc(array_len);
   ASSERT_NOT_NULL(setpoints);
   memset(setpoints, 0, array_len);
   rpm_square = malloc(array_len);
   ASSERT_NOT_NULL(rpm_square);
   memset(rpm_square, 0, array_len);

   LOG(LL_INFO, "initializing model/controller");
   pos_init();
   ne_speed_ctrl_init(REALTIME_PERIOD);
   att_ctrl_init();
   yaw_ctrl_init();
   u_ctrl_init();
   u_speed_init();
   navi_init();

   LOG(LL_INFO, "initializing command interface");
   cmd_init();

   motors_state_init();
   blackbox_init();

   /* init flight logic: */
   flight_logic_init();

   /* init calibration data: */
   cal_init(&gyro_cal, 3, 1000);

   cal_ahrs_init();
   flight_state_init(50, 150, 4.0);
   
   piid_init(REALTIME_PERIOD);

   interval_init(&gyro_move_interval);
   gps_data_init(&gps_data);

   mag_decl_init();
   cal_init(&rc_cal, 3, 500);

   tsfloat_t acc_fg;
   opcd_param_t params[] =
   {
      {"acc_fg", &acc_fg},
      OPCD_PARAMS_END
   };
   opcd_params_apply("main.", params);
   filter1_lp_init(&lp_filter, tsfloat_get(&acc_fg), 0.06, 3);

   cm_init();
   mon_init();
   LOG(LL_INFO, "entering main loop");
}
Beispiel #12
0
/// The Unix version of the function which actually runs and audits the
/// child command. The child command is run via fork/exec/wait while
/// this process sticks around to become the "monitor".
/// The monitor waits for the child to exit and in the meantime it
/// processes audit reports sent from exiting subordinate commands.
/// @param[in] exe      the path to this program (not the audited program)
/// @param[in] argv     a standard arg vector such as is passed to main()
/// @param[in] logfile  the name of a file to which log data is written, or NULL
/// @return 0 on success, nonzero otherwise
int
run_cmd(CCS exe, CS *argv, CCS logfile)
{
    CS path;
    pid_t childpid;
    int reuseaddr = 1;
    struct timeval master_timeout, timeout;
    int64_t session_timeout, last_heartbeat, heartbeat_interval;
    int sockmin = 3, sockmax = 0;
    int *listeners;
    unsigned long ports;
    fd_set listen_fds;
    fd_set master_read_fds;
    int sret;
    char *pdir;
    char *shlibdir = NULL;
    int sync_pipe[2];
    int wstat = 0;
    unsigned int i;

    path = argv[0];

    ports = prop_get_ulong(P_MONITOR_LISTENERS);
    listeners = putil_malloc(ports * sizeof(int));

    // If a logfile is requested, fork a "tee" and connect
    // stdout and stderr to it. This requires that we trust
    // tee to go away when its stdin is closed.
    // Note: we could put this on the child side of the fork
    // and see only the "real" build messages, but this way
    // is more compatible with Windows and potentially more
    // informative. Kind of mind-bending though.
    if (logfile) {
	const char *loglevel;

	loglevel = prop_get_str(P_SERVER_LOG_LEVEL);
	if (loglevel && !strcmp(loglevel, "OFF")) {
	    if (!(logfp = fopen(logfile, "w"))) {
		putil_syserr(2, logfile);
	    }
	} else {
	    char *tcmd, *tsf;

	    tsf = prop_is_true(P_LOG_TIME_STAMP) ? " --log-time-stamp" : "";
	    if (asprintf(&tcmd, "%s --log-file \"%s\" --log-tee%s",
		    exe, logfile, tsf) >= 0) {
		if (!(logfp = popen(tcmd, "w"))) {
		    putil_syserr(2, logfile);
		}
		putil_free(tcmd);
	    }
	}

	if (logfp) {
	    if ((dup2(fileno(logfp), fileno(stdout)) == -1)) {
		putil_syserr(2, logfile);
	    }

	    if ((dup2(fileno(logfp), fileno(stderr)) == -1)) {
		putil_syserr(2, logfile);
	    }
	}

	// Show the initial command and start time iff output is to a logfile.
	if (vb_bitmatch(VB_STD)) {
	    CCS cmdline;
	    time_t now;

	    cmdline = util_requote_argv(argv);
	    fprintf(vb_get_stream(), "+ %s\n", cmdline);
	    putil_free(cmdline);
	    time(&now);
	    vb_printf(VB_ON, "STARTED: %s", util_strtrim(ctime(&now)));
	}
    }

    // This property allows the entire auditing process to be dummied out;
    // we simply run the specified command, wait for it, and return.
    if (prop_is_true(P_EXECUTE_ONLY)) {
	if ((childpid = fork()) < 0) {
	    putil_syserr(2, "fork");
	} else if (childpid == 0) {
	    execvp(path, argv);
	    putil_syserr(2, path);
	} else {
	    if (waitpid(childpid, &wstat, 0) == -1) {
		putil_syserr(0, path);
		ExitStatus = 5;
	    } else if (WIFEXITED(wstat)) {
		ExitStatus = WEXITSTATUS(wstat);
	    } else {
		ExitStatus = 2;
	    }
	    return ExitStatus;
	}
    }

    // The heartbeat interval is the number of seconds allowed
    // before we send a server heartbeat ping to keep the server
    // HTTP session alive.  The Tomcat default is 30 minutes
    // but there's no standard default, so we set the default
    // expicitly in the server's web.xml file. This allows us to
    // assume that default via HTTP_SESSION_TIMEOUT_SECS_DEFAULT.

    master_timeout.tv_sec = prop_get_ulong(P_MONITOR_TIMEOUT_SECS);
    master_timeout.tv_usec = 0;
    session_timeout = prop_get_ulong(P_SESSION_TIMEOUT_SECS);
    if (session_timeout) {
	if ((session_timeout / 4 < master_timeout.tv_sec)) {
	    master_timeout.tv_sec = session_timeout / 4;
	}
	heartbeat_interval = session_timeout / 2;
    } else {
	heartbeat_interval = HTTP_SESSION_TIMEOUT_SECS_DEFAULT / 2;
    }

    // This is really only required on Windows.
    util_socket_lib_init();

    // The grandparent dir of this exe becomes the base where
    // we look for the preloaded library.
    if (!(pdir = putil_dirname(exe)) || !(shlibdir = putil_dirname(pdir))) {
	putil_syserr(2, "dirname(exe)");
    }
    putil_free(pdir);

    // Special case for truly "raw" output. There's no need
    // for a monitor process here; just inject and exec.
    if (shlibdir && prop_is_true(P_NO_MONITOR)) {
	libinterposer_preload_on(AUDITOR, shlibdir);
	execvp(path, argv);
	putil_syserr(2, path);
    }

    // This pipe will be used to ensure that the child doesn't get rolling
    // before the parent process is ready for its audits.
    if (pipe(sync_pipe) == -1) {
	putil_syserr(2, "pipe(sync_pipe)");
    }

    {
	struct sockaddr_in addr;
	socklen_t addrlen;
	char *portstr;
	size_t len;
	u_short port;

	// Max digits needed to represent a 32-bit value plus ':' is 11.
	len = ports * 11;
	portstr = putil_calloc(len, 1);

	for (i = 0; i < ports; i++) {
	    if ((listeners[i] = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
		putil_syserr(2, "socket()");
	    }

	    if (setsockopt(listeners[i], SOL_SOCKET, SO_REUSEADDR,
			   &reuseaddr, sizeof(reuseaddr)) == SOCKET_ERROR) {
		putil_syserr(2, "SO_REUSEADDR");
	    }

	    addrlen = sizeof(addr);
	    memset(&addr, 0, addrlen);
	    addr.sin_family = PF_INET;
	    addr.sin_addr.s_addr = INADDR_ANY;
	    addr.sin_port = htons(0);

	    if (bind(listeners[i], (struct sockaddr *)&addr, addrlen)) {
		putil_syserr(2, "bind()");
	    }

	    if (getsockname(listeners[i], (struct sockaddr *)&addr, &addrlen)) {
		putil_syserr(2, "getsockname");
	    }

	    port = ntohs(addr.sin_port);
	    snprintf(endof(portstr), len - strlen(portstr), "%u:", port);
	}

	prop_override_str(P_MONITOR_PORT, portstr);
	putil_free(portstr);
    }

    if ((childpid = fork()) < 0) {
	putil_syserr(2, "fork");
    } else if (childpid == 0) {
	char sync_buf[2];
	struct sockaddr_in dest_addr;
	int nfd;

	/*****************************************************************
	 * CHILD
	 *****************************************************************/

	// Not needed on child side.
	for (i = 0; i < ports; i++) {
	    fcntl(listeners[i], F_SETFD, fcntl(listeners[i], F_GETFD) | FD_CLOEXEC);
	}

	// We must wait till the parent has established its socket
	// before letting the build run. Otherwise we might try to
	// connect to it before it's ready.
	close(sync_pipe[1]);
	read(sync_pipe[0], sync_buf, 1);
	close(sync_pipe[0]);

	// Turn on the auditor.
	if (shlibdir) {
	    libinterposer_preload_on(AUDITOR, shlibdir);
	    putil_free(shlibdir);
	}

	// Run the command under control of the audit lib.
	execvp(path, argv);

	// Give an error if we were unable to exec at all.
	putil_die("%s: %s", path, strerror(errno));

	// The parent will be blocking on the first listening socket and needs
	// to hear from us on exec error. Send a special code telling
	// it to shut down gracefully.
	if ((nfd = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
	    putil_syserr(2, "socket()");
	}

	memset(&dest_addr, 0, sizeof(dest_addr));
	dest_addr.sin_family = PF_INET;
	dest_addr.sin_addr.s_addr = inet_addr(prop_get_str(P_MONITOR_HOST));
	dest_addr.sin_port = htons(strtoul(prop_get_str(P_MONITOR_PORT), NULL, 0));

	if ((connect(nfd, (struct sockaddr *)&dest_addr,
		     sizeof(struct sockaddr))) == -1) {
	    putil_syserr(2, "connect()");
	}

	// Tell the parent to abort the mission.
	write(nfd, "!\n", 2);

	close(nfd);

	_exit(2);
    }

    putil_free(shlibdir);

    /*********************************************************************
     * PARENT
     *********************************************************************/

    _sig_setup();

    last_heartbeat = time(NULL);

    // Bump the number of allowed file descriptors to the maximum,
    // because the monitor is likely to use a fair number. There
    // is no real bound on fds in use since the monitor may behave
    // asynchronously with respect to both audited child processes
    // and HTTP connections to the server.
    _maximize_fds();

    // Perform any one-time initializations related to the monitor.
    mon_init();

    // This pipe is used as a belt-and-suspenders method for letting
    // the monitor know that the build is done.
    if (pipe(done_pipe) == -1) {
	putil_syserr(2, "pipe(done_pipe)");
    }

    FD_ZERO(&master_read_fds);
    FD_ZERO(&listen_fds);

    // Add the read end of the self-pipe to the master set.
    FD_SET(done_pipe[0], &master_read_fds);
    sockmax = done_pipe[0];

    for (i = 0; i < ports; i++) {
	// Set up these sockets as listeners.
	if (listen(listeners[i], SOMAXCONN) == SOCKET_ERROR) {
	    putil_syserr(2, "listen");
	}

	// Add the listening sockets to the master set.
	FD_SET(listeners[i], &master_read_fds);

	// And to the listener set
	FD_SET(listeners[i], &listen_fds);

	// Keep track of the highest-numbered live socket.
	sockmax = (listeners[i] > sockmax) ? listeners[i] : sockmax;
    }

    // Alert the child that we're ready to roll.
    close(sync_pipe[0]);
    close(sync_pipe[1]);

    // The select loop.
    // Some network gurus argue that select should never be used
    // with blocking descriptors, but that's what we do here. Never looked
    // into why they say so but this should be run past an expert.
    while (!doneflag) {
	int fd;
	fd_set read_fds;

	// We have to reset the timeout because some implementations
	// of select modify it. This could cause it to busy-wait
	// as the timeout becomes zero.
	timeout = master_timeout;

	// Initialize the read fdset to its top-of-loop state.
	read_fds = master_read_fds;

	sret = select(sockmax + 1, &read_fds, NULL, NULL, &timeout);

	if (sret == SOCKET_ERROR) {
#if defined(EINTR)
	    if (errno == EINTR) {
		continue;
	    }
#endif	/*!EINTR*/
	    putil_syserr(2, "select");
	} else {
	    // We like to ping the server once in a while, partly
	    // to make sure it's still there but primarily to keep
	    // its session alive.
	    if (prop_has_value(P_SERVER)) {
		int64_t now;

		now = time(NULL);
		if ((now - last_heartbeat) >= heartbeat_interval) {
		    http_heartbeat(now - last_heartbeat);
		    last_heartbeat = now;
		}
	    }

	    // Continue on select timeout.
	    if (sret == 0) {
		continue;
	    }
	}

	for (i = 0; i < ports; i++) {
	    int found = 0;

	    if (FD_ISSET(listeners[i], &read_fds)) {
		SOCKET newfd;

		// Accept a new connection.
		if ((newfd = accept(listeners[i], NULL, NULL)) == INVALID_SOCKET) {
		    putil_syserr(2, "accept");
		}

		// Add it to the master set
		FD_SET(newfd, &master_read_fds);

		// Keep track of the highest numbered socket
		if (newfd > sockmax) {
		    sockmax = newfd;
		}

		found++;
	    }

	    if (found)
		continue;
	}

	// This can be turned on with a signal.
	if (dumpflag) {
	    mon_dump();
	    dumpflag = 0;
	}

	// Run through existing connections looking for data
	for (fd = sockmin; fd <= sockmax; fd++) {
	    CS buffer, buftmp, line;

	    if (FD_ISSET(fd, &listen_fds) || !FD_ISSET(fd, &read_fds)) {
		continue;
	    }

	    buffer = _read_available(fd);

	    for (buftmp = buffer, line = util_strsep(&buftmp, "\n");
		     line && *line; line = util_strsep(&buftmp, "\n")) {

		if (!strcmp(line, DONE_TOKEN)) {
		    // If the top-level process has ended, we have
		    // to be finished.
		    vb_printf(VB_MON, "DONE: %lu", childpid);
		    doneflag = 1;
		} else {
		    unsigned monrc;
		    CCS winner;

		    monrc = mon_record(line, &ExitStatus, NULL, &winner);

		    if (monrc & MON_NEXT) {
			// Nothing more to do - hit me again.
		    } else if (monrc & MON_ERR) {
			// Nothing more to do - error already handled.
		    } else if (monrc & MON_CANTRUN) {
			// This means the top-level process was unable
			// to run at all.
			doneflag = 1;
			break;
		    } else if (monrc & MON_SOA) {
			char ack[ACK_BUFFER_SIZE];

			if (monrc & MON_RECYCLED) {
			    // Tell auditor we recycled so it can exit.
			    snprintf(ack, sizeof(ack), "%s\n", winner);
			} else if (monrc & MON_STRICT) {
			    // Tell auditor we failed a requirement.
			    snprintf(ack, sizeof(ack), "%s\n", ACK_FAILURE);
			    ExitStatus = 3;
			} else if (monrc & MON_AGG) {
			    // Tell auditor this command is aggregated.
			    snprintf(ack, sizeof(ack), "%s\n", ACK_OK_AGG);
			} else {
			    // No special message - carry on.
			    snprintf(ack, sizeof(ack), "%s\n", ACK_OK);
			}

			if (util_send_all(fd, ack, strlen(ack), 0) == -1) {
			    putil_syserr(0, "send(ack)");
			}

			if (monrc & MON_TOP) {
			    if (Started) {
				mon_ptx_end(ExitStatus, logfile);
			    }
			    mon_ptx_start();
			    Started = 1;
			}
		    } else if (monrc & MON_EOA) {
			// Nothing more to do - end processing handled elsewhere
		    } else {
			putil_warn("unrecognized line '%s'", line);
		    }
		}
	    }

	    // We've reached EOF on a particular delivery;
	    // close the socket, remove it from the select mask, and
	    // return to the loop.
	    close(fd);
	    FD_CLR(fd, &master_read_fds);

	    putil_free(buffer);
	}

	http_async_transfer(0);
    }

    // Wait for ending child, reap its exit code.
    if (waitpid(childpid, &wstat, 0) == -1) {
	putil_syserr(0, path);
	ExitStatus = 5;
    }
    if (WIFEXITED(wstat)) {
	if (ExitStatus == 0) {
	    ExitStatus = WEXITSTATUS(wstat);
	}
    } else {
	if (WIFSIGNALED(wstat)) {
#if defined(__hpux)
	    // HACK - no strsignal on HPUX 11.00
	    putil_error("%s: %s%s", path, "",
			WCOREDUMP(wstat) ? " (coredump)" : "");
#else	/*__hpux*/
	    putil_error("%s: %s%s", path, strsignal(WTERMSIG(wstat)),
			WCOREDUMP(wstat) ? " (coredump)" : "");
#endif	/*__hpux*/
	}
	ExitStatus = 2;
    }

    mon_ptx_end(ExitStatus, logfile);

    mon_fini();

    for (i = 0; i < ports; i++) {
	if (close(listeners[i]) == SOCKET_ERROR) {
	    putil_syserr(0, "close(socket)");
	}
    }

    util_socket_lib_fini();

    return ExitStatus;
}
Beispiel #13
0
int
main(void)
{
    int i, result;
    flint_rand_t state;
    ctx_t ctx;

    printf("mul_mon... ");
    fflush(stdout);

    _randinit(state);

    ctx_init_mpq(ctx);

    /* Check aliasing of a and b */
    for (i = 0; i < 1000; i++)
    {
        mpoly_t a, b;
        mon_t m;
        long n, d, N;

        n = n_randint(state, MON_MAX_VARS) + 1;
        d = n_randint(state, 50) + 1;
        N = n_randint(state, 50) + 1;

        mon_init(m);
        mon_randtest(m, state, n, d);

        mpoly_init(a, n, ctx);
        mpoly_init(b, n, ctx);
        mpoly_randtest(a, state, d, N, ctx);

        mpoly_mul_mon(b, a, m, ctx);
        mpoly_mul_mon(a, a, m, ctx);

        result = (mpoly_equal(a, b, ctx));
        if (!result)
        {
            printf("FAIL:\n");
            mpoly_print(a, ctx); printf("\n");
            mpoly_print(b, ctx); printf("\n");
            mon_print(m, n); printf("\n");
            abort();
        }

        mpoly_clear(a, ctx);
        mpoly_clear(b, ctx);
        mon_clear(m);
    }

    /* Check (b*c) + (b*d) = b*(c+d) */
    for (i = 0; i < 1000; i++)
    {
        mpoly_t  a1, a2, c1, c2;
        mon_t b;
        long n, d, N;

        n = n_randint(state, MON_MAX_VARS) + 1;
        d = n_randint(state, 50) + 1;
        N = n_randint(state, 50) + 1;

        mon_init(b);
        mon_randtest(b, state, n, d);

        mpoly_init(a1, n, ctx);
        mpoly_init(a2, n, ctx);
        mpoly_init(c1, n, ctx);
        mpoly_init(c2, n, ctx);
        mpoly_randtest(c1, state, d, N, ctx);
        mpoly_randtest(c2, state, d, N, ctx);

        mpoly_mul_mon(a1, c1, b, ctx);
        mpoly_mul_mon(a2, c2, b, ctx);
        mpoly_add(a1, a1, a2, ctx);

        mpoly_add(c1, c1, c2, ctx);
        mpoly_mul_mon(a2, c1, b, ctx);

        result = (mpoly_equal(a1, a2, ctx));
        if (!result)
        {
            printf("FAIL:\n");
            mpoly_print(a1, ctx); printf("\n");
            mpoly_print(a2, ctx); printf("\n");
            mon_print(b, n); printf("\n");
            mpoly_print(c1, ctx); printf("\n");
            mpoly_print(c2, ctx); printf("\n");
            abort();
        }

        mpoly_clear(a1, ctx);
        mpoly_clear(a2, ctx);
        mpoly_clear(c1, ctx);
        mpoly_clear(c2, ctx);
        mon_clear(b);
    }

    _randclear(state);
    _fmpz_cleanup();
    printf("PASS\n");
    return EXIT_SUCCESS;
}
Beispiel #14
0
bool InitAll(const char *vmdir)
{
	// Check ROM version
	if (!CheckROM()) {
		ErrorAlert(STR_UNSUPPORTED_ROM_TYPE_ERR);
		return false;
	}

#if EMULATED_68K
	// Set CPU and FPU type (UAE emulation)
	switch (ROMVersion) {
		case ROM_VERSION_64K:
		case ROM_VERSION_PLUS:
		case ROM_VERSION_CLASSIC:
			CPUType = 0;
			FPUType = 0;
			TwentyFourBitAddressing = true;
			break;
		case ROM_VERSION_II:
			CPUType = PrefsFindInt32("cpu");
			if (CPUType < 2) CPUType = 2;
			if (CPUType > 4) CPUType = 4;
			FPUType = PrefsFindBool("fpu") ? 1 : 0;
			if (CPUType == 4) FPUType = 1;	// 68040 always with FPU
			TwentyFourBitAddressing = true;
			break;
		case ROM_VERSION_32:
			CPUType = PrefsFindInt32("cpu");
			if (CPUType < 2) CPUType = 2;
			if (CPUType > 4) CPUType = 4;
			FPUType = PrefsFindBool("fpu") ? 1 : 0;
			if (CPUType == 4) FPUType = 1;	// 68040 always with FPU
			TwentyFourBitAddressing = false;
			break;
	}
	CPUIs68060 = false;
#endif

	// Load XPRAM
	XPRAMInit(vmdir);

	// Load XPRAM default values if signature not found
	if (XPRAM[0x0c] != 0x4e || XPRAM[0x0d] != 0x75
	 || XPRAM[0x0e] != 0x4d || XPRAM[0x0f] != 0x63) {
		D(bug("Loading XPRAM default values\n"));
		memset(XPRAM, 0, 0x100);
		XPRAM[0x0c] = 0x4e;	// "NuMc" signature
		XPRAM[0x0d] = 0x75;
		XPRAM[0x0e] = 0x4d;
		XPRAM[0x0f] = 0x63;
		XPRAM[0x01] = 0x80;	// InternalWaitFlags = DynWait (don't wait for SCSI devices upon bootup)
		XPRAM[0x10] = 0xa8;	// Standard PRAM values
		XPRAM[0x11] = 0x00;
		XPRAM[0x12] = 0x00;
		XPRAM[0x13] = 0x22;
		XPRAM[0x14] = 0xcc;
		XPRAM[0x15] = 0x0a;
		XPRAM[0x16] = 0xcc;
		XPRAM[0x17] = 0x0a;
		XPRAM[0x1c] = 0x00;
		XPRAM[0x1d] = 0x02;
		XPRAM[0x1e] = 0x63;
		XPRAM[0x1f] = 0x00;
		XPRAM[0x08] = 0x13;
		XPRAM[0x09] = 0x88;
		XPRAM[0x0a] = 0x00;
		XPRAM[0x0b] = 0xcc;
		XPRAM[0x76] = 0x00;	// OSDefault = MacOS
		XPRAM[0x77] = 0x01;
	}

	// Set boot volume
	int16 i16 = PrefsFindInt32("bootdrive");
	XPRAM[0x78] = i16 >> 8;
	XPRAM[0x79] = i16 & 0xff;
	i16 = PrefsFindInt32("bootdriver");
	XPRAM[0x7a] = i16 >> 8;
	XPRAM[0x7b] = i16 & 0xff;

	// Init drivers
	SonyInit();
	DiskInit();
	CDROMInit();
	SCSIInit();

#if SUPPORTS_EXTFS
	// Init external file system
	ExtFSInit();
#endif

	// Init serial ports
	SerialInit();

	// Init network
	EtherInit();

	// Init Time Manager
	TimerInit();

	// Init clipboard
	ClipInit();

	// Init ADB
	ADBInit();

	// Init audio
	AudioInit();

	// Init video
	if (!VideoInit(ROMVersion == ROM_VERSION_64K || ROMVersion == ROM_VERSION_PLUS || ROMVersion == ROM_VERSION_CLASSIC))
		return false;

	// Set default video mode in XPRAM
	XPRAM[0x56] = 0x42;	// 'B'
	XPRAM[0x57] = 0x32;	// '2'
	const monitor_desc &main_monitor = *VideoMonitors[0];
	XPRAM[0x58] = uint8(main_monitor.depth_to_apple_mode(main_monitor.get_current_mode().depth));
	XPRAM[0x59] = 0;

#if EMULATED_68K
	// Init 680x0 emulation (this also activates the memory system which is needed for PatchROM())
	if (!Init680x0())
		return false;
#endif

	// Install ROM patches
	if (!PatchROM()) {
		ErrorAlert(STR_UNSUPPORTED_ROM_TYPE_ERR);
		return false;
	}

#if ENABLE_MON
	// Initialize mon
	mon_init();
	mon_read_byte = mon_read_byte_b2;
	mon_write_byte = mon_write_byte_b2;
#endif

	return true;
}
Beispiel #15
0
int main(int argc, char *argv[])
{
    mon_t m, m1, m2, *list;
    long i, len;
    char *out, *out1, *out2;

    printf("t-all\n");
    printf("=====\n");
    fflush(stdout);

    /* INIT, FROM_STRING, CLEAR */
    
    mon_init(m);
    mon_set_str(m, "3  1 1 1");
    
    out = mon_get_str(m, 3);
    printf("m = {%s}\n", out);
    free(out);
    
    mon_clear(m);
    
    /* GENERATE_BY_DEGREE */

    printf("Generating all monomials in X, Y, Z of degree 6\n");
    list = mon_generate_by_degree(&len, 3, 6);
    for (i = 0; i < len; i++)
    {
        out = mon_get_str_pretty(list[i], 3, NULL);
        printf("    %s\n", out);
        free(out);
    }
    for (i = 0; i < len; i++)
        mon_clear(list[i]);
    free(list);
    
    printf("Generating all monomials in X, Y, Z of degree 6\n");
    list = mon_generate_by_degree_invlex(&len, 3, 6);
    for (i = 0; i < len; i++)
    {
        out = mon_get_str_pretty(list[i], 3, NULL);
        printf("    %lu - %s\n", list[i], out);
        free(out);
    }
    for (i = 0; i < len; i++)
        mon_clear(list[i]);
    free(list);
    
    /* IS_ONE, DEGREE */

    mon_init(m);
    mon_set_str(m, "3  2 0 1");
    out = mon_get_str_pretty(m, 3, "XYZ");
    printf("Is %s equal to one?  %d\n", out, mon_is_one(m));
    printf("Degree: %d\n", mon_degree(m));
    free(out);
    mon_clear(m);
    
    mon_init(m);
    mon_set_str(m, "3  0 0 0");
    out = mon_get_str_pretty(m, 3, "XYZ");
    printf("Is %s equal to one?  %d\n", out, mon_is_one(m));
    printf("Degree: %d\n", mon_degree(m));
    free(out);
    mon_clear(m);
    
    /* MUL, DIVIDES, INVLEX */
    
    mon_init(m);
    mon_init(m1);
    mon_init(m2);
    mon_set_str(m1, "3  2 0 1");
    mon_set_str(m2, "3  0 1 0");
    mon_mul(m, m1, m2);
    out = mon_get_str_pretty(m, 3, "XYZ");
    printf("Product is [2 0 1] [0 1 0] = %s\n", out);
    free(out);
    printf("Divides?  %d\n", mon_divides(m1, m2));
    printf("INVLEX: %d\n", mon_cmp_invlex(m1, m2));
    mon_clear(m1);
    mon_clear(m2);
    mon_clear(m);
    
    /* DIVIDES, DIV, INVLEX */
    
    mon_init(m);
    mon_init(m1);
    mon_init(m2);
    mon_set_str(m1, "3  1 0 1");
    mon_set_str(m2, "3  1 1 3");
    mon_mul(m, m1, m2);
    out = mon_get_str_pretty(m, 3, "XYZ");
    printf("Product is [1 0 1] [1 1 3] = %s\n", out);
    free(out);
    printf("Divides?  %d\n", mon_divides(m1, m2));
    mon_div(m, m2, m1);
    out = mon_get_str_pretty(m, 3, "XYZ");
    printf("Quotient: %s\n", out);
    free(out);
    printf("INVLEX: %d\n", mon_cmp_invlex(m1, m2));
    mon_clear(m1);
    mon_clear(m2);
    mon_clear(m);
    
    /* INVLEX */
    
    mon_set_str(m1, "3  6 0 0");
    mon_set_str(m2, "3  0 0 6");
    out1 = mon_get_str_pretty(m1, 3, NULL);
    out2 = mon_get_str_pretty(m2, 3, NULL);
    printf("CMP_INVLEX(%s, %s) = %d\n", out1, out2, mon_cmp_invlex(m1, m2));
    free(out1);
    free(out2);

    printf("... ");

    printf("PASS\n");
    fflush(stdout);
    return EXIT_SUCCESS;
}
mon_t * mon_generate_by_degree_invlex(long * len, int n, int d)
{
    mon_t * st;  /* Stack (from the bottom), list (from the top) */
    int * sums;
    int * inds;
    int i;       /* Pointer to the top of the stack */
    int j;       /* Pointer to the bottom of the list */
    int N;       /* $\binom{n-1+d}{d}$ */
    int sum, ind;
    mon_t m;
    exp_t exp;
    
    /* Special case d == 0 */
    if (d == 0)
    {
        st = malloc(sizeof(mon_t));
        if (!st)
        {
            printf("ERROR (mon_generate_by_degree_invlex).  Memory allocation failed.\n");
            abort();
        }
        
        mon_init(st[0]);
        *len = 1;
        return st;
    }
    
    N = mon_binom(n - 1 + d, d);
    
    st   = malloc(N * sizeof(mon_t));
    sums = malloc(N * sizeof(int));
    inds = malloc(N * sizeof(int));
    if (!st || !sums || !inds)
    {
        printf("ERROR (mon_generate_by_degree_invlex).  Memory allocation failed.\n");
        abort();
    }
    
    for (i = 0; i < N; i++)
        mon_init(st[i]);
    
    mon_init(m);
    
    i = 0;
    sums[0] = 0;
    inds[0] = n - 1;
    j = N;
    
    while (i >= 0)
    {
        mon_set(m, st[i]);
        ind = inds[i];
        sum = sums[i];
        i--;
        
        if (ind > 0)
        {
            for (exp = 0; exp <= d - sum; exp++)
            {
                i++;
                mon_set(st[i], m);
                mon_inc_exp(st[i], ind, exp);
                inds[i] = ind - 1;
                sums[i] = sum + exp;
            }
        }
        else
        {
            j--;
            mon_set(st[j], m);
            mon_inc_exp(st[j], ind, d - sum);
        }
    }
    
    mon_clear(m);
    free(sums);
    free(inds);
    
    *len = N;
    return st;
}
Beispiel #17
0
int main(int argc, char **argv)
{
	char str[256];
	int16 i16;
	HANDLE rom_fh;
	const char *rom_path;
	uint32 rom_size;
	DWORD actual;
	uint8 *rom_tmp;

	// Initialize variables
	RAMBase = 0;

	// Print some info
	printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
	printf(" %s\n", GetString(STR_ABOUT_TEXT2));

	// Read preferences
	PrefsInit(NULL, argc, argv);

	// Parse command line arguments
	for (int i=1; i<argc; i++) {
		if (strcmp(argv[i], "--help") == 0) {
			usage(argv[0]);
		} else if (argv[i][0] == '-') {
			fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
			usage(argv[0]);
		}
	}

	// Check we are using a Windows NT kernel >= 4.0
	OSVERSIONINFO osvi;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	if (!GetVersionEx(&osvi)) {
		ErrorAlert("Could not determine OS type");
		QuitEmulator();
	}
	win_os = osvi.dwPlatformId;
	win_os_major = osvi.dwMajorVersion;
	if (win_os != VER_PLATFORM_WIN32_NT || win_os_major < 4) {
		ErrorAlert(GetString(STR_NO_WIN32_NT_4));
		QuitEmulator();
	}

	// Check that drivers are installed
	if (!check_drivers())
		QuitEmulator();

	// Load win32 libraries
	KernelInit();

	// FIXME: default to DIB driver
	if (getenv("SDL_VIDEODRIVER") == NULL)
	    putenv("SDL_VIDEODRIVER=windib");

	// Initialize SDL system
	int sdl_flags = 0;
#ifdef USE_SDL_VIDEO
	sdl_flags |= SDL_INIT_VIDEO;
#endif
#ifdef USE_SDL_AUDIO
	sdl_flags |= SDL_INIT_AUDIO;
#endif
	assert(sdl_flags != 0);
	if (SDL_Init(sdl_flags) == -1) {
		char str[256];
		sprintf(str, "Could not initialize SDL: %s.\n", SDL_GetError());
		ErrorAlert(str);
		goto quit;
	}
	atexit(SDL_Quit);

#ifdef ENABLE_MON
	// Initialize mon
	mon_init();
#endif

	// Install SIGSEGV handler for CPU emulator
	if (!sigsegv_install_handler(sigsegv_handler)) {
		sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}

	// Initialize VM system
	vm_init();

	// Get system info
	PVR = 0x00040000;			// Default: 604
	CPUClockSpeed = 100000000;	// Default: 100MHz
	BusClockSpeed = 100000000;	// Default: 100MHz
	TimebaseSpeed =  25000000;	// Default:  25MHz
	PVR = 0x000c0000;			// Default: 7400 (with AltiVec)
	D(bug("PVR: %08x (assumed)\n", PVR));

	// Init system routines
	SysInit();

	// Show preferences editor
	if (!PrefsFindBool("nogui"))
		if (!PrefsEditor())
			goto quit;

	// Create areas for Kernel Data
	if (!kernel_data_init())
		goto quit;
	kernel_data = (KernelData *)Mac2HostAddr(KERNEL_DATA_BASE);
	emulator_data = &kernel_data->ed;
	KernelDataAddr = KERNEL_DATA_BASE;
	D(bug("Kernel Data at %p (%08x)\n", kernel_data, KERNEL_DATA_BASE));
	D(bug("Emulator Data at %p (%08x)\n", emulator_data, KERNEL_DATA_BASE + offsetof(KernelData, ed)));

	// Create area for DR Cache
	if (vm_mac_acquire(DR_EMULATOR_BASE, DR_EMULATOR_SIZE) < 0) {
		sprintf(str, GetString(STR_DR_EMULATOR_MMAP_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}
	dr_emulator_area_mapped = true;
	if (vm_mac_acquire(DR_CACHE_BASE, DR_CACHE_SIZE) < 0) {
		sprintf(str, GetString(STR_DR_CACHE_MMAP_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}
	dr_cache_area_mapped = true;
	DRCacheAddr = (uint32)Mac2HostAddr(DR_CACHE_BASE);
	D(bug("DR Cache at %p (%08x)\n", DRCacheAddr, DR_CACHE_BASE));

	// Create area for SheepShaver data
	if (!SheepMem::Init()) {
		sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}

	// Create area for Mac ROM
	if (vm_mac_acquire(ROM_BASE, ROM_AREA_SIZE) < 0) {
		sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}
	ROMBase = ROM_BASE;
	ROMBaseHost = Mac2HostAddr(ROMBase);
	rom_area_mapped = true;
	D(bug("ROM area at %p (%08x)\n", ROMBaseHost, ROMBase));

	// Create area for Mac RAM
	RAMSize = PrefsFindInt32("ramsize");
	if (RAMSize < 8*1024*1024) {
		WarningAlert(GetString(STR_SMALL_RAM_WARN));
		RAMSize = 8*1024*1024;
	}
	RAMBase = 0;
	if (vm_mac_acquire(RAMBase, RAMSize) < 0) {
		sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
		ErrorAlert(str);
		goto quit;
	}
	RAMBaseHost = Mac2HostAddr(RAMBase);
	ram_area_mapped = true;
	D(bug("RAM area at %p (%08x)\n", RAMBaseHost, RAMBase));

	if (RAMBase > ROMBase) {
		ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
		goto quit;
	}

	// Load Mac ROM
	rom_path = PrefsFindString("rom");
	rom_fh = CreateFile(rom_path && *rom_path ? rom_path : ROM_FILE_NAME,
						GENERIC_READ, 0, NULL, OPEN_EXISTING,
						FILE_ATTRIBUTE_NORMAL, NULL);

	if (rom_fh == INVALID_HANDLE_VALUE) {
		rom_fh = CreateFile(ROM_FILE_NAME2,
							GENERIC_READ, 0, NULL, OPEN_EXISTING,
							FILE_ATTRIBUTE_NORMAL, NULL);

		if (rom_fh == INVALID_HANDLE_VALUE) {
			ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
			goto quit;
		}
	}
	printf(GetString(STR_READING_ROM_FILE));
	rom_size = GetFileSize(rom_fh, NULL);
	rom_tmp = new uint8[ROM_SIZE];
	ReadFile(rom_fh, (void *)rom_tmp, ROM_SIZE, &actual, NULL);
	CloseHandle(rom_fh);
	
	// Decode Mac ROM
	if (!DecodeROM(rom_tmp, actual)) {
		if (rom_size != 4*1024*1024) {
			ErrorAlert(GetString(STR_ROM_SIZE_ERR));
			goto quit;
		} else {
			ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
			goto quit;
		}
	}
	delete[] rom_tmp;
	
	// Initialize native timers
	timer_init();

	// Initialize everything
	if (!InitAll(NULL))
		goto quit;
	D(bug("Initialization complete\n"));

	// Write protect ROM
	vm_protect(ROMBaseHost, ROM_AREA_SIZE, VM_PAGE_READ);

	// Start 60Hz thread
	tick_thread_cancel = false;
	tick_thread_active = ((tick_thread = create_thread(tick_func)) != NULL);
	SetThreadPriority(tick_thread, THREAD_PRIORITY_ABOVE_NORMAL);
	D(bug("Tick thread installed (%ld)\n", tick_thread));

	// Start NVRAM watchdog thread
	memcpy(last_xpram, XPRAM, XPRAM_SIZE);
	nvram_thread_cancel = false;
	nvram_thread_active = ((nvram_thread = create_thread(nvram_func, NULL)) != NULL);
	SetThreadPriority(nvram_thread, THREAD_PRIORITY_BELOW_NORMAL);
	D(bug("NVRAM thread installed (%ld)\n", nvram_thread));

	// Get my thread ID and jump to ROM boot routine
	emul_thread = GetCurrentThread();
	D(bug("Jumping to ROM\n"));
#ifdef _MSC_VER
	__try {
#endif
		jump_to_rom(ROMBase + 0x310000);
#ifdef _MSC_VER
	} __except (main_exception_filter(GetExceptionInformation())) {}
#endif
	D(bug("Returned from ROM\n"));

quit:
	Quit();
	return 0;
}
Beispiel #18
0
/*------------------------------------------------------------------------
 *  sysinit  --  initialize all Xinu data structeres and devices
 *------------------------------------------------------------------------
 */
LOCAL
sysinit()
{
	static	long	currsp;
	int	i,j, avail;
	struct	pentry	*pptr;
	struct	sentry	*sptr;
	struct	mblock	*mptr;
	SYSCALL pfintr();

	/*********************/
	set_evec(14, pfintr);

	pptr = &proctab[NULLPROC]; /* initialize null process entry */
	/*********************/
	

	numproc = 0;			/* initialize system variables */
	nextproc = NPROC-1;
	nextsem = NSEM-1;
	nextqueue = NPROC;		/* q[0..NPROC-1] are processes */

	/* initialize free memory list */
	/* PC version has to pre-allocate 640K-1024K "hole" */
	if (maxaddr+1 > HOLESTART) {
		memlist.mnext = mptr = (struct mblock *) roundmb(&end);
		mptr->mnext = (struct mblock *)HOLEEND;
		mptr->mlen = (int) truncew(((unsigned) HOLESTART -
	     		 (unsigned)&end));
        mptr->mlen -= 4;

		mptr = (struct mblock *) HOLEEND;
		mptr->mnext = 0;
		mptr->mlen = (int) truncew((unsigned)maxaddr - HOLEEND -
	      		NULLSTK);
/*
		mptr->mlen = (int) truncew((unsigned)maxaddr - (4096 - 1024 ) *  4096 - HOLEEND - NULLSTK);
*/
	} else {
		/* initialize free memory list */
		memlist.mnext = mptr = (struct mblock *) roundmb(&end);
		mptr->mnext = 0;
		mptr->mlen = (int) truncew((unsigned)maxaddr - (int)&end -
			NULLSTK);
	}
	

	for (i=0 ; i<NPROC ; i++)	/* initialize process table */
		proctab[i].pstate = PRFREE;


#ifdef	MEMMARK
	_mkinit();			/* initialize memory marking */
#endif

#ifdef	RTCLOCK
	clkinit();			/* initialize r.t.clock	*/
#endif

	mon_init();     /* init monitor */

#ifdef NDEVS
	for (i=0 ; i<NDEVS ; i++ ) {	    
	    init_dev(i);
	}
#endif

	pptr = &proctab[NULLPROC];	/* initialize null process entry */
	pptr->pstate = PRCURR;
	for (j=0; j<7; j++)
		pptr->pname[j] = "prnull"[j];
	pptr->plimit = (WORD)(maxaddr + 1) - NULLSTK;
	pptr->pbase = (WORD) maxaddr - 3;
/*
	pptr->plimit = (WORD)(maxaddr + 1) - NULLSTK - (4096 - 1024 )*4096;
	pptr->pbase = (WORD) maxaddr - 3 - (4096-1024)*4096;
*/
	pptr->pesp = pptr->pbase-4;	/* for stkchk; rewritten before used */
	*( (int *)pptr->pbase ) = MAGIC;
	pptr->paddr = (WORD) nulluser;
	pptr->pargs = 0;
	pptr->pprio = 0;
	currpid = NULLPROC;
	
	
	for (i=0 ; i<NSEM ; i++) {	/* initialize semaphores */
		(sptr = &semaph[i])->sstate = SFREE;
		sptr->sqtail = 1 + (sptr->sqhead = newqueue());
	}

	rdytail = 1 + (rdyhead=newqueue());/* initialize ready list */

	init_bsm();
	init_frm();

	kprintf("initialize page tables for null process\n");
	init_glb_pgs(glb_pg_tbl_frm_mapping);
	// init pg dir for proc 0
	frame_t *pg_dir = get_free_frame();
	init_pg_dir(pg_dir, NULLPROC);
	pptr->pdbr = pg_dir->frm_num;
	pptr->pd = pg_dir;
	return(OK);
}
/*------------------------------------------------------------------------
 *  sysinit  --  initialize all Xinu data structeres and devices
 *------------------------------------------------------------------------
 */
LOCAL int sysinit()
{
	int	i,j;
	struct	pentry	*pptr;
	struct	sentry	*sptr;
	struct	mblock	*mptr;

	numproc = 0;			/* initialize system variables */
	nextproc = NPROC-1;
	nextsem = NSEM-1;
	nextqueue = NPROC;		/* q[0..NPROC-1] are processes */

	/* initialize free memory list */
	/* PC version has to pre-allocate 640K-1024K "hole" */
	if (maxaddr+1 > (char *)HOLESTART) {
		memlist.mnext = mptr = (struct mblock *) roundmb(&end);
		mptr->mnext = (struct mblock *)HOLEEND;
		mptr->mlen = (int) truncew(((unsigned) HOLESTART -
	     		 (unsigned)&end));
        mptr->mlen -= 4;

		mptr = (struct mblock *) HOLEEND;
		mptr->mnext = 0;
		mptr->mlen = (int) truncew((unsigned)maxaddr - HOLEEND -
	      		NULLSTK);
	} else {
		/* initialize free memory list */
		memlist.mnext = mptr = (struct mblock *) roundmb(&end);
		mptr->mnext = 0;
		mptr->mlen = (int) truncew((unsigned)maxaddr - (int)&end -
			NULLSTK);
	}
	

	for (i=0 ; i<NPROC ; i++)	/* initialize process table */
		proctab[i].pstate = PRFREE;

	pptr = &proctab[NULLPROC];	/* initialize null process entry */
	pptr->pstate = PRCURR;
	for (j=0; j<7; j++)
		pptr->pname[j] = "prnull"[j];
	pptr->plimit = (WORD)(maxaddr + 1) - NULLSTK;
	pptr->pbase = (WORD) maxaddr - 3;
	pptr->pesp = pptr->pbase-4;	/* for stkchk; rewritten before used */
	*( (int *)pptr->pbase ) = MAGIC;
	pptr->paddr = (WORD) nulluser;
	pptr->pargs = 0;
	pptr->pprio = 0;
	currpid = NULLPROC;

	for (i=0 ; i<NSEM ; i++) {	/* initialize semaphores */
		(sptr = &semaph[i])->sstate = SFREE;
		sptr->sqtail = 1 + (sptr->sqhead = newqueue());
	}

	rdytail = 1 + (rdyhead=newqueue());/* initialize ready list */

#ifdef	MEMMARK
	_mkinit();			/* initialize memory marking */
#endif

#ifdef	RTCLOCK
	clkinit();			/* initialize r.t.clock	*/
#endif

	pci_init();	/* PCI */

	mon_init();	/* init monitor */
//	ripinit();

#ifdef NDEVS
	for (i=0 ; i<NDEVS ; i++ ) {	    
	    init_dev(i);
	}
#endif
	buf_init();
	return(OK);
}
Beispiel #20
0
int main (int argc, char *argv[])
{
	int       r;
	char      **optarg;
	int       run, nomon;
	unsigned  drive;
	char      *cfg;
	ini_sct_t *sct;

	cfg = NULL;
	run = 0;
	nomon = 0;

	pce_log_init();
	pce_log_add_fp (stderr, 0, MSG_INF);

	par_cfg = ini_sct_new (NULL);

	if (par_cfg == NULL) {
		return (1);
	}

	ini_str_init (&par_ini_str);

	while (1) {
		r = pce_getopt (argc, argv, &optarg, opts);

		if (r == GETOPT_DONE) {
			break;
		}

		if (r < 0) {
			return (1);
		}

		switch (r) {
		case '?':
			print_help();
			return (0);

		case 'V':
			print_version();
			return (0);

		case 'b':
			par_disk_delay_valid |= 1;
			par_disk_delay[0] = (unsigned) strtoul (optarg[0], NULL, 0);
			break;

		case 'B':
			drive = strtoul (optarg[0], NULL, 0);

			if ((drive < 1) || (drive >= SONY_DRIVES)) {
				fprintf (stderr, "%s: bad drive number (%u)\n",
					argv[0], drive
				);
				return (1);
			}

			drive -= 1;

			par_disk_delay_valid |= 1U << drive;
			par_disk_delay[drive] = (unsigned) strtoul (optarg[1], NULL, 0);
			break;

		case 'c':
			cfg = optarg[0];
			break;

		case 'd':
			pce_path_set (optarg[0]);
			break;

		case 'i':
			if (ini_read_str (par_cfg, optarg[0])) {
				fprintf (stderr,
					"%s: error parsing ini string (%s)\n",
					argv[0], optarg[0]
				);
				return (1);
			}
			break;

		case 'I':
			ini_str_add (&par_ini_str, optarg[0], "\n", NULL);
			break;

		case 'l':
			pce_log_add_fname (optarg[0], MSG_DEB);
			break;

		case 'p':
			ini_str_add (&par_ini_str, "cpu.model = \"",
				optarg[0], "\"\n"
			);
			break;

		case 'q':
			pce_log_set_level (stderr, MSG_ERR);
			break;

		case 'r':
			run = 1;
			break;

		case 'R':
			nomon = 1;
			break;

		case 's':
			ini_str_add (&par_ini_str, "cpu.speed = ",
				optarg[0], "\n"
			);
			break;

		case 't':
			par_terminal = optarg[0];
			break;

		case 'v':
			pce_log_set_level (stderr, MSG_DEB);
			break;

		case 0:
			fprintf (stderr, "%s: unknown option (%s)\n",
				argv[0], optarg[0]
			);
			return (1);

		default:
			return (1);
		}
	}

	mac_log_banner();

	if (pce_load_config (par_cfg, cfg)) {
		return (1);
	}

	sct = ini_next_sct (par_cfg, NULL, "macplus");

	if (sct == NULL) {
		sct = par_cfg;
	}

	if (ini_str_eval (&par_ini_str, sct, 1)) {
		return (1);
	}

	atexit (mac_atexit);

#ifdef PCE_ENABLE_SDL
	SDL_Init (0);
#endif

	pce_path_ini (sct);

	signal (SIGINT, &sig_int);
	signal (SIGSEGV, &sig_segv);
	signal (SIGTERM, &sig_term);

	pce_console_init (stdin, stdout);

	par_sim = mac_new (sct);

	mon_init (&par_mon);
	mon_set_cmd_fct (&par_mon, mac_cmd, par_sim);
	mon_set_msg_fct (&par_mon, mac_set_msg, par_sim);
	mon_set_get_mem_fct (&par_mon, par_sim->mem, mem_get_uint8);
	mon_set_set_mem_fct (&par_mon, par_sim->mem, mem_set_uint8);
	mon_set_memory_mode (&par_mon, 0);

	cmd_init (par_sim, cmd_get_sym, cmd_set_sym);
	mac_cmd_init (par_sim, &par_mon);

	mac_reset (par_sim);

	if (nomon) {
		while (par_sim->brk != PCE_BRK_ABORT) {
			mac_run (par_sim);
		}
	}
	else if (run) {
		mac_run (par_sim);
		if (par_sim->brk != PCE_BRK_ABORT) {
			pce_puts ("\n");
		}
	}
	else {
		pce_puts ("type 'h' for help\n");
	}

	if (par_sim->brk != PCE_BRK_ABORT) {
		mon_run (&par_mon);
	}

	mac_del (par_sim);

#ifdef PCE_ENABLE_SDL
	SDL_Quit();
#endif

	mon_free (&par_mon);
	pce_console_done();
	pce_log_done();

	return (0);
}