示例#1
0
文件: main.c 项目: XVilka/OpenEC
//! You expected it: This routine is expected never to exit
void main (void)
{
    port_init();
    watchdog_init();
    timer_gpt3_init();
    adc_init();
    cursors_init();
    power_init();

    uart_init();

    /* enable interrupts. */
    EA = 1;

    get_board_id();
    startup_message();

    dump_xdata_sfr();
    gpio_check_IO_direction();
    dump_gpio();
    dump_mcs51();

tx_drain();  // oops, UART routines seem not yet clean

    print_states_ruler();
    print_states_enable = 1;
    print_states();
    print_states_enable = 0;

    save_old_states();
    states.number = 0;

    manufacturing_print_all();

    ow_init();
    timer1_init();
    battery_charging_table_init();

    LED_CHG_G_OFF();
    LED_CHG_R_OFF();
    LED_PWR_OFF();

    /* The main loop contains several state machines handling
       various subsystems on the EC.
       The idea is to have each subroutine return as quickly
       as it can (no busy wait unless for a _very_ short delay).
       Also the subroutines should be pretty much self contained.

       Unless it is noted _here_ no state machine should need
       more than xxx microseconds before returning control.
       When a state machine returns control it is expected to
       have the variables it is working on in a consistent
       state. Period (just in case it was missed:^)

       If it helps: you may want to think of the main loop
       as a round-robin cooperative scheduler without the
       overhead this usually implies. This works well if, well,
       if _all_ routines within the main loop cooperate well.
     */
    while(1)
    {
        STATES_TIMESTAMP();

        busy = handle_command();
        busy |= handle_cursors();
        handle_leds();
        handle_power();
        handle_ds2756_requests();
        handle_ds2756_readout();
        busy |= handle_battery_charging_table();

        watchdog_all_up_and_well |= WATCHDOG_MAIN_LOOP_IS_FINE;

        print_states();

        monitor();

        handle_debug();

        sleep_if_allowed();
    }
}
示例#2
0
static long process(calcoutRecord *prec)
{
    rpvtStruct *prpvt = prec->rpvt;
    int doOutput;

    if (!prec->pact) {
        prec->pact = TRUE;
        /* if some links are CA, check connections */
        if (prpvt->caLinkStat != NO_CA_LINKS) {
            checkLinks(prec);
        }
        if (fetch_values(prec) == 0) {
            if (calcPerform(&prec->a, &prec->val, prec->rpcl)) {
                recGblSetSevr(prec, CALC_ALARM, INVALID_ALARM);
            } else {
                prec->udf = isnan(prec->val);
            }
        }
        checkAlarms(prec);
        /* check for output link execution */
        switch (prec->oopt) {
        case calcoutOOPT_Every_Time:
            doOutput = 1;
            break;
        case calcoutOOPT_On_Change:
            doOutput = ! (fabs(prec->pval - prec->val) <= prec->mdel);
            break;
        case calcoutOOPT_Transition_To_Zero:
            doOutput = ((prec->pval != 0.0) && (prec->val == 0.0));
            break;
        case calcoutOOPT_Transition_To_Non_zero:
            doOutput = ((prec->pval == 0.0) && (prec->val != 0.0));
            break;
        case calcoutOOPT_When_Zero:
            doOutput = (prec->val == 0.0);
            break;
        case calcoutOOPT_When_Non_zero:
            doOutput = (prec->val != 0.0);
            break;
        default:
	    doOutput = 0;
            break;
        }
        prec->pval = prec->val;
        if (doOutput) {
            if (prec->odly > 0.0) {
                prec->dlya = 1;
                recGblGetTimeStamp(prec);
                db_post_events(prec, &prec->dlya, DBE_VALUE);
                callbackRequestProcessCallbackDelayed(&prpvt->doOutCb,
                        prec->prio, prec, (double)prec->odly);
                return 0;
            } else {
                prec->pact = FALSE;
                execOutput(prec);
                if (prec->pact) return 0;
                prec->pact = TRUE;
            }
        }
        recGblGetTimeStamp(prec);
    } else { /* pact == TRUE */
        if (prec->dlya) {
            prec->dlya = 0;
            recGblGetTimeStamp(prec);
            db_post_events(prec, &prec->dlya, DBE_VALUE);
            /* Make pact FALSE for asynchronous device support*/
            prec->pact = FALSE;
            execOutput(prec);
            if (prec->pact) return 0;
            prec->pact = TRUE;
        } else {/*Device Support is asynchronous*/
            writeValue(prec);
            recGblGetTimeStamp(prec);
        }
    }
    monitor(prec);
    recGblFwdLink(prec);
    prec->pact = FALSE;
    return 0;
}
示例#3
0
/*-------------------------------------------------------------------------+
| function: rotina associada a thread da interface com utilizador
+--------------------------------------------------------------------------*/
void threadInterface_func(cyg_addrword_t data) {

	cmd_ini(0, NULL);
	monitor();
}
static long process(longoutRecord *prec)
{
	struct longoutdset	*pdset = (struct longoutdset *)(prec->dset);
	long		 status=0;
	epicsInt32	 value;
	unsigned char    pact=prec->pact;

	if( (pdset==NULL) || (pdset->write_longout==NULL) ) {
		prec->pact=TRUE;
		recGblRecordError(S_dev_missingSup,(void *)prec,"write_longout");
		return(S_dev_missingSup);
	}
	if (!prec->pact) {
		if((prec->dol.type != CONSTANT)
                && (prec->omsl == menuOmslclosed_loop)) {
			status = dbGetLink(&(prec->dol),DBR_LONG,
				&value,0,0);
			if (prec->dol.type!=CONSTANT && RTN_SUCCESS(status))
				prec->udf=FALSE;
		}
		else {
			value = prec->val;
		}
		if (!status) convert(prec,value);
	}

	/* check for alarms */
	checkAlarms(prec);

        if (prec->nsev < INVALID_ALARM )
                status=writeValue(prec); /* write the new value */
        else {
                switch (prec->ivoa) {
                    case (menuIvoaContinue_normally) :
                        status=writeValue(prec); /* write the new value */
                        break;
                    case (menuIvoaDon_t_drive_outputs) :
                        break;
                    case (menuIvoaSet_output_to_IVOV) :
                        if(prec->pact == FALSE){
                                prec->val=prec->ivov;
                        }
                        status=writeValue(prec); /* write the new value */
                        break;
                    default :
                        status=-1;
                        recGblRecordError(S_db_badField,(void *)prec,
                                "longout:process Illegal IVOA field");
                }
        }

	/* check if device support set pact */
	if ( !pact && prec->pact ) return(0);
	prec->pact = TRUE;

	recGblGetTimeStamp(prec);

	/* check event list */
	monitor(prec);

	/* process the forward scan link record */
	recGblFwdLink(prec);

	prec->pact=FALSE;
	return(status);
}
示例#5
0
nsresult
DOMStorageDBThread::InsertDBOp(DOMStorageDBThread::DBOperation* aOperation)
{
  MonitorAutoLock monitor(mThreadObserver->GetMonitor());

  // Sentinel to don't forget to delete the operation when we exit early.
  nsAutoPtr<DOMStorageDBThread::DBOperation> opScope(aOperation);

  if (NS_FAILED(mStatus)) {
    MonitorAutoUnlock unlock(mThreadObserver->GetMonitor());
    aOperation->Finalize(mStatus);
    return mStatus;
  }

  if (mStopIOThread) {
    // Thread use after shutdown demanded.
    MOZ_ASSERT(false);
    return NS_ERROR_NOT_INITIALIZED;
  }

  switch (aOperation->Type()) {
  case DBOperation::opPreload:
  case DBOperation::opPreloadUrgent:
    if (mPendingTasks.IsScopeUpdatePending(aOperation->Scope())) {
      // If there is a pending update operation for the scope first do the flush
      // before we preload the cache.  This may happen in an extremely rare case
      // when a child process throws away its cache before flush on the parent
      // has finished.  If we would preloaded the cache as a priority operation 
      // before the pending flush, we would have got an inconsistent cache content.
      mFlushImmediately = true;
    } else if (mPendingTasks.IsScopeClearPending(aOperation->Scope())) {
      // The scope is scheduled to be cleared, so just quickly load as empty.
      // We need to do this to prevent load of the DB data before the scope has
      // actually been cleared from the database.  Preloads are processed
      // immediately before update and clear operations on the database that
      // are flushed periodically in batches.
      MonitorAutoUnlock unlock(mThreadObserver->GetMonitor());
      aOperation->Finalize(NS_OK);
      return NS_OK;
    }
    // NO BREAK

  case DBOperation::opGetUsage:
    if (aOperation->Type() == DBOperation::opPreloadUrgent) {
      SetHigherPriority(); // Dropped back after urgent preload execution
      mPreloads.InsertElementAt(0, aOperation);
    } else {
      mPreloads.AppendElement(aOperation);
    }

    // DB operation adopted, don't delete it.
    opScope.forget();

    // Immediately start executing this.
    monitor.Notify();
    break;

  default:
    // Update operations are first collected, coalesced and then flushed
    // after a short time.
    mPendingTasks.Add(aOperation);

    // DB operation adopted, don't delete it.
    opScope.forget();

    ScheduleFlush();
    break;
  }

  return NS_OK;
}
示例#6
0
文件: main.cpp 项目: preesm/spider
int main(){
	#if DSP
		PlatformK2Dsp platform(0);
	#else
		PlatformLinux platform(0);
	#endif


	FILE* fres;
	printf("Start\n");
	try{
		fres = fopen("omp/omp_homo.csv", "w+");
		int iter = 1;
		for(iter=1; iter<=17; iter++){
			printf("h**o %d\n", iter);
			OmpMonitor monitor(0);
			hclm_sched(
					/*MNext*/ 	0,
					/*MStart*/ 	12,
					/*N*/ 		iter,
					/*NbS*/ 	4000,
					&monitor);
			monitor.saveData(iter, "h**o");
			fprintf(fres, "%d,%d\n", iter, monitor.getEndTime());
		}
		fclose(fres);

		fres = fopen("omp/omp_inc.csv", "w+");
		for(iter=1; iter<=17; iter++){
			printf("inc %d\n", iter);
			OmpMonitor monitor(0);
			hclm_sched(
					/*MNext*/ 	1,
					/*MStart*/ 	1,
					/*N*/ 		iter,
					/*NbS*/ 	4000,
					&monitor);
			monitor.saveData(iter, "inc");
			fprintf(fres, "%d,%d\n", iter, monitor.getEndTime());
		}
		fclose(fres);

		fres = fopen("omp/omp_dec.csv", "w+");
		for(iter=1; iter<=17; iter++){
			printf("dec %d\n", iter);
			OmpMonitor monitor(0);
			hclm_sched(
					/*MNext*/ 	-1,
					/*MStart*/ 	iter,
					/*N*/ 		iter,
					/*NbS*/ 	4000,
					&monitor);
			monitor.saveData(iter, "dec");
			fprintf(fres, "%d,%d\n", iter, monitor.getEndTime());
		}
		fclose(fres);

	}catch(char const* ex){
		printf("Error: %s\n",ex);
	}
	printf("End\n");

	return 0;
}
示例#7
0
文件: trap.c 项目: joe-cai/jos
static void
trap_dispatch(struct Trapframe *tf)
{
    // Handle processor exceptions.
    // LAB 3: Your code here.
    if (tf->tf_trapno == T_BRKPT) {
	print_trapframe(tf);
	// cprintf("Breakpoint!\n");
	while (1)
	    monitor(NULL);
    } else if (tf->tf_trapno == T_PGFLT) {
	page_fault_handler(tf);
	return;
    } else if (tf->tf_trapno == T_SYSCALL) {
	uint32_t syscallno;
	uint32_t a1, a2, a3, a4, a5;
	syscallno = tf->tf_regs.reg_eax;
	a1 = tf->tf_regs.reg_edx;
	a2 = tf->tf_regs.reg_ecx;
	a3 = tf->tf_regs.reg_ebx;
	a4 = tf->tf_regs.reg_edi;
	a5 = tf->tf_regs.reg_esi;
	int32_t ret = syscall(syscallno, a1, a2, a3, a4, a5);
	tf->tf_regs.reg_eax = ret;
	return;
    }

    // Handle spurious interrupts
    // The hardware sometimes raises these because of noise on the
    // IRQ line or other reasons. We don't care.
    if (tf->tf_trapno == IRQ_OFFSET + IRQ_SPURIOUS) {
	cprintf("Spurious interrupt on irq 7\n");
	print_trapframe(tf);
	return;
    }

    // Handle clock interrupts. Don't forget to acknowledge the
    // interrupt using lapic_eoi() before calling the scheduler!
    // LAB 4: Your code here.
    if (tf->tf_trapno == IRQ_OFFSET + IRQ_TIMER) {
	time_tick();
	lapic_eoi(); /* what's that? */
	sched_yield();
    }

    // Handle keyboard and serial interrupts.
    // LAB 5: Your code here.
    if (tf->tf_trapno == IRQ_OFFSET + IRQ_KBD) {
	kbd_intr();
	return;
    }
    if (tf->tf_trapno == IRQ_OFFSET + IRQ_SERIAL) {
	serial_intr();
	return;
    }

    // Unexpected trap: The user process or the kernel has a bug.
    print_trapframe(tf);
    if (tf->tf_cs == GD_KT)
	panic("unhandled trap in kernel");
    else {
	env_destroy(curenv);
	return;
    }
}
示例#8
0
static void
trap_dispatch(struct Trapframe *tf)
{
	// Handle processor exceptions.
	// Ashish
	switch (tf->tf_trapno) {
		case T_PGFLT:
			page_fault_handler(tf);
			return;
		case T_BRKPT:
			monitor(tf);
			return;
		case T_SYSCALL:
			tf->tf_regs.reg_rax = syscall(tf->tf_regs.reg_rax, tf->tf_regs.reg_rdx, tf->tf_regs.reg_rcx, 
							tf->tf_regs.reg_rbx, tf->tf_regs.reg_rdi, tf->tf_regs.reg_rsi);
			return;
	}

	// Handle spurious interrupts
	// The hardware sometimes raises these because of noise on the
	// IRQ line or other reasons. We don't care.
	if (tf->tf_trapno == IRQ_OFFSET + IRQ_SPURIOUS) {
		cprintf("Spurious interrupt on irq 7\n");
		print_trapframe(tf);
		return;
	}

	// Handle clock interrupts. Don't forget to acknowledge the
	// interrupt using lapic_eoi() before calling the scheduler!
	// Ashish
	if (tf->tf_trapno == IRQ_OFFSET + IRQ_TIMER) {
		time_tick(); //TODO: Multi CPU?
		lapic_eoi();
		sched_yield();
		return;
	}

	// Add time tick increment to clock interrupts.
	// Be careful! In multiprocessors, clock interrupts are
	// triggered on every CPU.
	// LAB 6: Your code here.


	// Handle keyboard and serial interrupts.
	//Ashish
	if (tf->tf_trapno == IRQ_OFFSET + IRQ_KBD) {
		kbd_intr();
		return;
	}
	if (tf->tf_trapno == IRQ_OFFSET + IRQ_SERIAL) {
		serial_intr();
		return;
	}

	// Unexpected trap: The user process or the kernel has a bug.
	print_trapframe(tf);
	if (tf->tf_cs == GD_KT)
		panic("unhandled trap in kernel");
	else {
		env_destroy(curenv);
		return;
	}
}
示例#9
0
void
main(int argc, char **argv)
{
	Word *w;
	char *s, *temp;
	char *files[256], **f = files, **ff;
	int sflag = 0;
	int i;
	int tfd = -1;
	Biobuf tb;
	Bufblock *buf;
	Bufblock *whatif;

	/*
	 *  start with a copy of the current environment variables
	 *  instead of sharing them
	 */

	Binit(&bout, 1, OWRITE);
	buf = newbuf();
	whatif = 0;
	USED(argc);
	for(argv++; *argv && (**argv == '-'); argv++)
	{
		bufcpy(buf, argv[0], strlen(argv[0]));
		insert(buf, ' ');
		switch(argv[0][1])
		{
		case 'a':
			aflag = 1;
			break;
		case 'd':
			if(*(s = &argv[0][2]))
				while(*s) switch(*s++)
				{
				case 'p':	debug |= D_PARSE; break;
				case 'g':	debug |= D_GRAPH; break;
				case 'e':	debug |= D_EXEC; break;
				}
			else
				debug = 0xFFFF;
			break;
		case 'e':
			explain = &argv[0][2];
			break;
		case 'f':
			if(*++argv == 0)
				badusage();
			*f++ = *argv;
			bufcpy(buf, argv[0], strlen(argv[0]));
			insert(buf, ' ');
			break;
		case 'i':
			iflag = 1;
			break;
		case 'k':
			kflag = 1;
			break;
		case 'n':
			nflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		case 't':
			tflag = 1;
			break;
		case 'u':
			uflag = 1;
			break;
		case 'w':
			if(whatif == 0)
				whatif = newbuf();
			else
				insert(whatif, ' ');
			if(argv[0][2])
				bufcpy(whatif, &argv[0][2], strlen(&argv[0][2]));
			else {
				if(*++argv == 0)
					badusage();
				bufcpy(whatif, &argv[0][0], strlen(&argv[0][0]));
			}
			break;
		default:
			badusage();
		}
	}
#ifdef	PROF
	{
		extern etext();
		monitor(main, etext, buf, sizeof buf, 300);
	}
#endif

	if(aflag)
		iflag = 1;
	usage();
	syminit();
	initenv();
	usage();

	/*
		assignment args become null strings
	*/
	temp = 0;
	for(i = 0; argv[i]; i++) if(utfrune(argv[i], '=')){
		bufcpy(buf, argv[i], strlen(argv[i]));
		insert(buf, ' ');
		if(tfd < 0){
			temp = maketmp();
			if(temp == 0) {
				perror("temp file");
				Exit();
			}
			if((tfd = create(temp, ORDWR, 0600)) < 0){
				perror(temp);
				Exit();
			}
			Binit(&tb, tfd, OWRITE);
		}
		Bprint(&tb, "%s\n", argv[i]);
		*argv[i] = 0;
	}
	if(tfd >= 0){
		Bflush(&tb);
		LSEEK(tfd, 0L, 0);
		parse("command line args", tfd, 1);
		remove(temp);
	}

	if (buf->current != buf->start) {
		buf->current--;
		insert(buf, 0);
	}
	symlook("MKFLAGS", S_VAR, (void *) stow(buf->start));
	buf->current = buf->start;
	for(i = 0; argv[i]; i++){
		if(*argv[i] == 0) continue;
		if(i)
			insert(buf, ' ');
		bufcpy(buf, argv[i], strlen(argv[i]));
	}
	insert(buf, 0);
	symlook("MKARGS", S_VAR, (void *) stow(buf->start));
	freebuf(buf);

	if(f == files){
		if(access(MKFILE, 4) == 0)
			parse(MKFILE, open(MKFILE, 0), 0);
	} else
		for(ff = files; ff < f; ff++)
			parse(*ff, open(*ff, 0), 0);
	if(DEBUG(D_PARSE)){
		dumpw("default targets", target1);
		dumpr("rules", rules);
		dumpr("metarules", metarules);
		dumpv("variables");
	}
	if(whatif){
		insert(whatif, 0);
		timeinit(whatif->start);
		freebuf(whatif);
	}
	execinit();
	/* skip assignment args */
	while(*argv && (**argv == 0))
		argv++;

	catchnotes();
	if(*argv == 0){
		if(target1)
			for(w = target1; w; w = w->next)
				mk(w->s);
		else {
			fprint(2, "mk: nothing to mk\n");
			Exit();
		}
	} else {
		if(sflag){
			for(; *argv; argv++)
				if(**argv)
					mk(*argv);
		} else {
			Word *head, *tail, *t;

			/* fake a new rule with all the args as prereqs */
			tail = 0;
			t = 0;
			for(; *argv; argv++)
				if(**argv){
					if(tail == 0)
						tail = t = newword(*argv);
					else {
						t->next = newword(*argv);
						t = t->next;
					}
				}
			if(tail->next == 0)
				mk(tail->s);
			else {
				head = newword("command line arguments");
				addrules(head, tail, strdup(""), VIR, mkinline, 0);
				mk(head->s);
			}
		}
	}
	if(uflag)
		prusage();
	exits(0);
}
示例#10
0
void breakpoint_handler(struct Trapframe *tf){
	monitor(tf);
}
示例#11
0
int sdl_window_info::complete_create()
{
	osd_dim temp(0,0);

	// clear out original mode. Needed on OSX
	if (fullscreen())
	{
		// default to the current mode exactly
		temp = monitor()->position_size().dim();

		// if we're allowed to switch resolutions, override with something better
		if (video_config.switchres)
			temp = pick_best_mode();
	}
	else if (m_windowed_dim.width() > 0)
	{
		// if we have a remembered size force the new window size to it
		temp = m_windowed_dim;
	}
	else if (m_startmaximized)
		temp = get_max_bounds(video_config.keepaspect );
	else
		temp = get_min_bounds(video_config.keepaspect );

	// create the window .....

	/* FIXME: On Ubuntu and potentially other Linux OS you should use
	 * to disable panning. This has to be done before every invocation of mame.
	 *
	 * xrandr --output HDMI-0 --panning 0x0+0+0 --fb 0x0
	 *
	 */
	osd_printf_verbose("Enter sdl_info::create\n");
	if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL) && !video_config.novideo)
	{
		SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

		/* FIXME: A reminder that gamma is wrong throughout MAME. Currently, SDL2.0 doesn't seem to
		    * support the following attribute although my hardware lists GL_ARB_framebuffer_sRGB as an extension.
		    *
		    * SDL_GL_SetAttribute( SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1 );
		    *
		    */
		m_extra_flags = SDL_WINDOW_OPENGL;
	}
	else
		m_extra_flags = 0;

#ifdef SDLMAME_MACOSX
	/* FIMXE: On OSX, SDL_WINDOW_FULLSCREEN_DESKTOP seems to be more reliable.
	 *        It however creates issues with white borders, i.e. the screen clear
	 *        does not work. This happens both with opengl and accel.
	 */
#endif

	// We need to workaround an issue in SDL 2.0.4 for OS X where setting the
	// relative mode on the mouse in fullscreen mode makes mouse events stop
	// It is fixed in the latest revisions so we'll assume it'll be fixed
	// in the next public SDL release as well
#if defined(SDLMAME_MACOSX) && SDL_VERSION_ATLEAST(2, 0, 2) // SDL_HINT_MOUSE_RELATIVE_MODE_WARP is introduced in 2.0.2
	SDL_version linked;
	SDL_GetVersion(&linked);
	int revision = SDL_GetRevisionNumber();

	// If we're running the exact version of SDL 2.0.4 (revision 10001) from the
	// SDL web site, we need to work around this issue and send the warp mode hint
	if (SDL_VERSION_EQUALS(linked, SDL_VERSIONNUM(2, 0, 4)) && revision == 10001)
	{
		osd_printf_verbose("Using warp mode for relative mouse in OS X SDL 2.0.4\n");
		SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1");
	}
#endif

	// create the SDL window
	// soft driver also used | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_MOUSE_FOCUS
	m_extra_flags |= (fullscreen() ?
			SDL_WINDOW_BORDERLESS | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE);

#if defined(SDLMAME_WIN32)
	SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
#endif

	// get monitor work area for centering
	osd_rect work = monitor()->usuable_position_size();

	// create the SDL window
	auto sdlwindow = SDL_CreateWindow(m_title,
			work.left() + (work.width() - temp.width()) / 2,
			work.top() + (work.height() - temp.height()) / 2,
			temp.width(), temp.height(), m_extra_flags);
	//window().sdl_window() = SDL_CreateWindow(window().m_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
	//      width, height, m_extra_flags);

	if  (sdlwindow == nullptr )
	{
		if (renderer().has_flags(osd_renderer::FLAG_NEEDS_OPENGL))
			osd_printf_error("OpenGL not supported on this driver: %s\n", SDL_GetError());
		else
			osd_printf_error("Window creation failed: %s\n", SDL_GetError());
		return 1;
	}

	set_platform_window(sdlwindow);

	if (fullscreen() && video_config.switchres)
	{
		SDL_DisplayMode mode;
		//SDL_GetCurrentDisplayMode(window().monitor()->handle, &mode);
		SDL_GetWindowDisplayMode(platform_window(), &mode);
		m_original_mode->mode = mode;
		mode.w = temp.width();
		mode.h = temp.height();
		if (m_win_config.refresh)
			mode.refresh_rate = m_win_config.refresh;

		SDL_SetWindowDisplayMode(platform_window(), &mode);    // Try to set mode
#ifndef SDLMAME_WIN32
		/* FIXME: Warp the mouse to 0,0 in case a virtual desktop resolution
		 * is in place after the mode switch - which will most likely be the case
		 * This is a hack to work around a deficiency in SDL2
		 */
		SDL_WarpMouseInWindow(platform_window(), 1, 1);
#endif
	}
	else
	{
		//SDL_SetWindowDisplayMode(window().sdl_window(), nullptr); // Use desktop
	}

	// show window

	SDL_ShowWindow(platform_window());
	//SDL_SetWindowFullscreen(window->sdl_window(), 0);
	//SDL_SetWindowFullscreen(window->sdl_window(), window->fullscreen());
	SDL_RaiseWindow(platform_window());

#ifdef SDLMAME_WIN32
	if (fullscreen())
		SDL_SetWindowGrab(platform_window(), SDL_TRUE);
#endif

	// set main window
	if (m_index > 0)
	{
		for (auto w : osd_common_t::s_window_list)
		{
			if (w->m_index == 0)
			{
				set_main_window(std::dynamic_pointer_cast<osd_window>(w));
				break;
			}
		}
	}
	else
	{
		// We must be the main window
		set_main_window(shared_from_this());
	}

	// update monitor resolution after mode change to ensure proper pixel aspect
	monitor()->refresh();
	if (fullscreen() && video_config.switchres)
		monitor()->update_resolution(temp.width(), temp.height());

	// initialize the drawing backend
	if (renderer().create())
		return 1;

	// Make sure we have a consistent state
	SDL_ShowCursor(0);
	SDL_ShowCursor(1);

	return 0;
}
示例#12
0
文件: trap.c 项目: amisharma/OSLAB
static void
trap_dispatch(struct Trapframe *tf)
{
	// Handle processor exceptions.
	// LAB 3: Your code here.
//<<<<<<< HEAD

	// Handle spurious interrupts
	// The hardware sometimes raises these because of noise on the
	// IRQ line or other reasons. We don't care.
	if (tf->tf_trapno == IRQ_OFFSET + IRQ_SPURIOUS) {
		cprintf("Spurious interrupt on irq 7\n");
		print_trapframe(tf);
		return;
	}
//cprintf("entering trap dispathc\n");
	// Handle clock interrupts. Don't forget to acknowledge the
	// interrupt using lapic_eoi() before calling the scheduler!
	// LAB 4: Your code here.

//<<<<<<< HEAD
	// Add time tick increment to clock interrupts.
	// Be careful! In multiprocessors, clock interrupts are
	// triggered on every CPU.
	// LAB 6: Your code here.


//=======
//<<<<<<< HEAD
//>>>>>>> lab5
	// Handle keyboard and serial interrupts.
	// LAB 5: Your code here.
	if(tf->tf_trapno==IRQ_OFFSET+IRQ_KBD)
	{
		//cprintf("IRQ_OFFSET+IRQ_KBD trap\n");
		kbd_intr();
		return;
	}
	if(tf->tf_trapno==IRQ_OFFSET+IRQ_SERIAL)
        {
                //cprintf("IRQ_OFFSET+IRQ_serial trap\n");
                serial_intr();
                return;
        }
//=======
//=======
	if(tf->tf_trapno==T_PGFLT)
	{
//		cprintf("pagefault handler\n");
		page_fault_handler(tf);
		return;
	} else if((tf->tf_trapno==T_GPFLT)) {
		print_trapframe(tf);
		return;
	}
	else if(tf->tf_trapno==T_BRKPT)
        {
//                cprintf("T_BRKPT");
		monitor(tf);
                return;
        }
	else if(tf->tf_trapno==T_SYSCALL)
	{//	cprintf("calling syscal'\n");
		tf->tf_regs.reg_rax =syscall(tf->tf_regs.reg_rax,tf->tf_regs.reg_rdx,tf->tf_regs.reg_rcx,tf->tf_regs.reg_rbx,tf->tf_regs.reg_rdi,tf->tf_regs.reg_rsi);
	//	cprintf("syscall exit\n");
		return;
	}
//>>>>>>> lab3
//>>>>>>> lab4
	// Unexpected trap: The user process or the kernel has a bug.
	else if(tf->tf_trapno == IRQ_OFFSET + IRQ_TIMER)
	{
		lapic_eoi();
		time_tick();
		sched_yield();
	}
	print_trapframe(tf);
	if (tf->tf_cs == GD_KT)
		panic("unhandled trap in kernel");
	else {
		cprintf("destroy env\n");
		env_destroy(curenv);
		return;
	}
//	cprintf("exiting trap_dispatch\n");
}
示例#13
0
/*!
  process the message mothed, it will be called by playback task.

  \param[in] p_handle playback handle
  \param[in] p_msg new message
  */
static void pb_single_step(handle_t handle, os_msg_t *p_msg)
{
  pb_handle_t *p_handle = (pb_handle_t *)handle;
  priv_data_t *p_data = &p_handle->data;
  play_param_t *p_play_param = NULL;
  
  if(p_msg != NULL)
  {
    switch(p_msg->content)
    {
      case NC_EVT_UNLOCKED:
      case NC_EVT_LOCKED:
        OS_PRINTF("!!!!!PB:PB_EVT_LOCK_RSL %d\n", 
                        NC_EVT_LOCKED == p_msg->content);
        if(p_data->status != PB_STOP)
        {
          if (check_same_tp(p_handle, &p_data->play_param))
          {
            OS_PRINTF("PB play ticks %d\n", mtos_ticks_get());
            do_play(p_handle, &p_data->play_param);
            p_data->status = PB_PLAYING;
            p_handle->data.pat_monitor_start = mtos_ticks_get();
            p_handle->data.pat_monitor_interval = 100;
            p_handle->p_policy->on_play(p_handle->p_policy->p_data, &p_data->play_param);
            p_data->sm = PB_SM_WAIT_VIDEO;
          }
          send_evt_to_ui(PB_EVT_LOCK_RSL, NC_EVT_LOCKED == p_msg->content, 0);
        }
      break;
      case PB_CMD_PLAY:
        OS_PRINTF("do lock ticks %d\n", mtos_ticks_get());
        p_play_param = (play_param_t *)p_msg->para1;
        memcpy(&p_data->play_param, p_play_param, sizeof(play_param_t));
        p_data->status = PB_PLAYING;
        do_play_chan_open(p_handle, &p_data->play_param);

        log_perf(LOG_AP_CHANGE_CHANNEL, TAB_PB_START, 0, 0);
        lock_tuner_1(p_handle, &p_data->play_param);
        p_data->sm = PB_SM_WAIT_LOCK;
        break;
      case PB_CMD_STOP:
        log_perf(LOG_AP_CHANGE_CHANNEL, TAB_PB_STOP, 
        (u32)(&p_data->play_param.inner.dvbs_lock_info.tp_rcv), (u32)(&p_data->play_param.pg_info));
        do_stop(p_handle, p_msg->para1);
        //pat_free(p_handle);
        OS_PRINTF("PB stop ticks %d\n", mtos_ticks_get());
        p_data->status = PB_STOP;
        //p_data->status.cur_pg_id = INVALID_PG_ID;
        p_data->sm = PB_SM_IDLE;
        break;
      case PB_CMD_STOP_SYNC:
        log_perf(LOG_AP_CHANGE_CHANNEL, TAB_PB_STOP_SYNC, 
        (u32)(&p_data->play_param.inner.dvbs_lock_info.tp_rcv), (u32)(&p_data->play_param.pg_info));
        do_stop(p_handle, p_msg->para1);
        OS_PRINTF("PB stop by sync ticks %d\n", mtos_ticks_get());
        p_data->status = PB_STOP;
        p_data->sm = PB_SM_WAIT_STOP;
        send_evt_to_ui(PB_EVT_STOPPED, 0, 0);
        break;
      case PB_CMD_SWITCH_AUDIO_CHANNEL:
        switch_audio_channel(p_handle, p_msg->para1, p_msg->para2);
        break;
      case PB_CMD_SET_MUTE:
        //avc_set_mute((BOOL)p_msg->para1, (BOOL)p_msg->para2);
        send_evt_to_ui(PB_EVT_SET_MUTE, 0, 0);
        break;
      case PB_CMD_SET_VOL:
        //avc_setvolume((u8)p_msg->para1);
        send_evt_to_ui(PB_EVT_SET_VOL, 0, 0);
        break;
      case PB_CMD_RESET_TVMODE:
        p_data->play_param.pg_info.tv_mode = (u16)p_msg->para1;
        break;
      case PB_CMD_RESET_VIDEO_ASPECT_MODE:
        p_data->play_param.pg_info.aspect_ratio = p_msg->para1;
        break;
      case DVB_TABLE_TIMED_OUT:
        if(p_msg->para1 == DVB_TABLE_ID_PAT)
        {
          p_data->pat_request_flag = 0;
        }
        if(p_msg->para1 == DVB_TABLE_ID_NIT_ACTUAL)
        {
          p_data->nit_request_flag = 0;
        }
        break;
      case DVB_PAT_FOUND:
        p_data->pat_request_flag = 0;
        break;
      case DVB_PAT_PMT_INFO:
        if(p_data->play_param.pg_info.s_id == p_msg->para2)
        {
          pmt_request(p_handle, (u16)p_msg->para1, (u16)p_msg->para2);
        }
        break;
      case DVB_PMT_FOUND:
        if((p_data->status == PB_PLAYING) && 
          (p_data->play_param.pg_info.s_id == (u32)(((pmt_t *)(p_msg->para1))->prog_num)))
        {
          do_dynamic_pid(p_handle, (pmt_t *)p_msg->para1);
          pmt_update_1(p_handle->data.p_sub_ttx_data, (pmt_t *)p_msg->para1);
        }
        else
        {
          subt_txt_info_reset_1(p_handle->data.p_sub_ttx_data);
        }
        break;
      case DVB_SDT_FOUND:
        if(p_data->status == PB_PLAYING)
        {
          do_revise_eid(p_handle, (sdt_t *)p_msg->para1);
        }
        if(p_data->play_param.lock_mode == SYS_DVBC)
        {
          pb_on_sdt_found(p_handle, (sdt_t *)p_msg->para1);
        }
        break;
      case DVB_NIT_FOUND:
        p_data->nit_request_flag = 0;
        pb_on_nit_found(p_handle, (nit_t *)p_msg->para1);
        break;
      //falcon debug
      case PB_CMD_START_TTX:
        vbi_ttx_start_vsb(p_msg->para1, p_msg->para2);
        break;
      case PB_CMD_STOP_TTX:
        vbi_ttx_stop_vsb();
       break;
      case PB_CMD_SET_TTX_LANG:
        set_ttx_lang_1(p_handle->data.p_sub_ttx_data, p_msg->para1);
        break;
      case PB_CMD_POST_TTX_KEY:
        post_ttx_key_1(p_handle->data.p_sub_ttx_data, p_msg->para1);
        break;
      case PB_CMD_SHOW_TTX:
        show_ttx_1(p_handle->data.p_sub_ttx_data, p_msg->para1);
        break;
      case PB_CMD_HIDE_TTX:
        if(!hide_ttx_1(p_handle->data.p_sub_ttx_data))
        {
          send_evt_to_ui(PB_EVT_HIDE_TTX, 0, 0);
        }
        break;
      case VBI_TTX_HIDED:
      case VBI_TTX_STOPPED:
                OS_PRINTF(">>>>>>VBI_TTX_HIDED!!!\n");
        send_evt_to_ui(PB_EVT_HIDE_TTX, 0, 0);
        break;
      case PB_CMD_START_VBI_INSERTER:
        start_vbi_inserter_1(p_handle->data.p_sub_ttx_data);
        break;
      case PB_CMD_STOP_VBI_INSERTER:
        stop_vbi_inserter_1(p_handle->data.p_sub_ttx_data);
        break;
      case PB_CMD_START_SUBT:
        start_subt_dec_1(p_handle->data.p_sub_ttx_data);
        break;
      case PB_CMD_STOP_SUBT:
        stop_subt_dec_1(p_handle->data.p_sub_ttx_data);
        break;
      case PB_CMD_STOP_SUBT_SYNC:
        stop_subt_dec_1(p_handle->data.p_sub_ttx_data);
        break;
      case SUBT_EVT_STOPPED:
        //OS_PRINTF("\n\n\n=====OK======\n\n\n");
        send_evt_to_ui(PB_EVT_SUBT_STOPED, 0, 0);
        break;
      case PB_CMD_SET_SUBT_SERVICE:
        set_subt_service_1(p_handle->data.p_sub_ttx_data,
          p_msg->para1, p_msg->para2);
        break;
      case PB_CMD_SHOW_SUBT:
        show_subtitle_1(p_handle->data.p_sub_ttx_data);
        break;
      case PB_CMD_HIDE_SUBT:
        if(FALSE == hide_subtitle_1(p_handle->data.p_sub_ttx_data))
        {
          send_evt_to_ui(PB_EVT_HIDE_SUBT, 0, 0);
        }
        //send_evt_to_ui(PB_EVT_HIDE_SUBT, 0, 0);
        break;
      default:
        break;
    }
  }
  else
  {
    switch(p_data->sm)
    {
      case PB_SM_IDLE:
        break;
      case PB_SM_WAIT_LOCK:
        break;
      case PB_SM_WAIT_VIDEO:
        if(wait_video_frame_1(p_handle))
        {
          log_perf(LOG_AP_CHANGE_CHANNEL, TAB_PB_DO_PLAY, 
          (u32)(&p_data->play_param.inner.dvbs_lock_info.tp_rcv), 
          (u32)(&p_data->play_param.pg_info));
          OS_PRINTF("video out ticks %d\n", mtos_ticks_get());
          p_data->signal_monitor_start = mtos_ticks_get();
          p_data->sm = PB_SM_MONITOR_SIGNAL;
          sdt_request(p_handle);
          p_data->pat_request_flag = 0;
        }
        break;
      case PB_SM_MONITOR_SIGNAL:
        if((mtos_ticks_get() - p_data->signal_monitor_start) > 50) // 50ticks
        {
          p_data->signal_monitor_start = mtos_ticks_get();
          monitor(p_handle);
        }

        if(((mtos_ticks_get() - p_data->pat_monitor_start) > p_data->pat_monitor_interval)
          && (!p_data->pat_request_flag))
        //  && (p_data->play_param.lock_mode == SYS_DVBS))
        {
          pat_request(p_handle);
          p_data->pat_request_flag = 1;
          p_data->pat_monitor_start = mtos_ticks_get();
          p_data->pat_monitor_interval = PAT_MONITOR_INTERVAL;
        }

         if(((mtos_ticks_get() - p_data->nit_monitor_start) > NIT_MONITOR_INTERVAL)
          && (!p_data->nit_request_flag)
          && (p_data->play_param.lock_mode == SYS_DVBC))
        {
          nit_request(p_handle);
          p_data->nit_request_flag = 1;
          p_data->nit_monitor_start = mtos_ticks_get();
        }
        break;
      case PB_SM_WAIT_STOP:
        p_data->sm = PB_SM_IDLE;
        break;
      default:
        break;
      }
    }
}
示例#14
0
int
main(int argc, char **argv)
{
	struct stackmark smark;
	volatile int state;
	char *shinit;
	uid_t uid;
	gid_t gid;

	uid = getuid();
	gid = getgid();

	max_user_fd = fcntl(0, F_MAXFD);
	if (max_user_fd < 2)
		max_user_fd = 2;

	setlocale(LC_ALL, "");

	posix = getenv("POSIXLY_CORRECT") != NULL;
#if PROFILE
	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
#endif
	state = 0;
	if (setjmp(main_handler.loc)) {
		/*
		 * When a shell procedure is executed, we raise the
		 * exception EXSHELLPROC to clean up before executing
		 * the shell procedure.
		 */
		switch (exception) {
		case EXSHELLPROC:
			rootpid = getpid();
			rootshell = 1;
			minusc = NULL;
			state = 3;
			break;

		case EXEXEC:
			exitstatus = exerrno;
			break;

		case EXERROR:
			exitstatus = 2;
			break;

		default:
			break;
		}

		if (exception != EXSHELLPROC) {
			if (state == 0 || iflag == 0 || ! rootshell ||
			    exception == EXEXIT)
				exitshell(exitstatus);
		}
		reset();
		if (exception == EXINT) {
			out2c('\n');
			flushout(&errout);
		}
		popstackmark(&smark);
		FORCEINTON;				/* enable interrupts */
		if (state == 1)
			goto state1;
		else if (state == 2)
			goto state2;
		else if (state == 3)
			goto state3;
		else
			goto state4;
	}
	handler = &main_handler;
#ifdef DEBUG
#if DEBUG >= 2
	debug = 1;	/* this may be reset by procargs() later */
#endif
	opentrace();
	trputs("Shell args:  ");  trargs(argv);
#if DEBUG >= 3
	set_debug(((DEBUG)==3 ? "_@" : "++"), 1);
#endif
#endif
	rootpid = getpid();
	rootshell = 1;
	init();
	initpwd();
	setstackmark(&smark);
	procargs(argc, argv);

	/*
	 * Limit bogus system(3) or popen(3) calls in setuid binaries,
	 * by requiring the -p flag
	 */
	if (!pflag && (uid != geteuid() || gid != getegid())) {
		setuid(uid);
		setgid(gid);
		/* PS1 might need to be changed accordingly. */
		choose_ps1();
	}

	if (argv[0] && argv[0][0] == '-') {
		state = 1;
		read_profile("/etc/profile");
 state1:
		state = 2;
		read_profile(".profile");
	}
 state2:
	state = 3;
	if ((iflag || !posix) &&
	    getuid() == geteuid() && getgid() == getegid()) {
		struct stackmark env_smark;

		setstackmark(&env_smark);
		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
			state = 3;
			read_profile(expandenv(shinit));
		}
		popstackmark(&env_smark);
	}
 state3:
	state = 4;
	line_number = 1;	/* undo anything from profile files */

	if (sflag == 0 || minusc) {
		static int sigs[] =  {
		    SIGINT, SIGQUIT, SIGHUP, 
#ifdef SIGTSTP
		    SIGTSTP,
#endif
		    SIGPIPE
		};
#define SIGSSIZE (sizeof(sigs)/sizeof(sigs[0]))
		size_t i;

		for (i = 0; i < SIGSSIZE; i++)
		    setsignal(sigs[i], 0);
	}

	if (minusc)
		evalstring(minusc, sflag ? 0 : EV_EXIT);

	if (sflag || minusc == NULL) {
 state4:	/* XXX ??? - why isn't this before the "if" statement */
		cmdloop(1);
		if (iflag) {
			out2str("\n");
			flushout(&errout);
		}
	}
#if PROFILE
	monitor(0);
#endif
	line_number = plinno;
	exitshell(exitstatus);
	/* NOTREACHED */
}
示例#15
0
// Write out the config file for the whole application
int configAppSaveXml()
{
	if (bCmdOptUsed) {
		return 1;
	}

	char configName[MAX_PATH];
	createConfigName(configName);

	try {
		char tempStr[64] = "";

		// root
		ticpp::Document doc;
		ticpp::Declaration decl("1.0", "UTF-8", "");
		doc.LinkEndChild(&decl);

		ticpp::Element root("configuration");
		setAttr(root, "version", configVersion);
		ticpp::Comment comment("Don't edit this file manually unless you know what you're doing\n" \
					APP_TITLE " will restore default settings when this file is deleted");
		doc.LinkEndChild(&comment);
		doc.LinkEndChild(&root);

		// title
		sprintf(tempStr, "0x%06X", nBurnVer);
		addTextNode(root, "version", tempStr);

		// emulation
		ticpp::Element emulation("emulation");
		root.LinkEndChild(&emulation);
		setAttr(emulation, "asm-68k", bBurnUseASM68K);
		setAttr(emulation, "all-ram", bDrvSaveAll);

		// video
		ticpp::Element video("video");
		root.LinkEndChild(&video);

		ticpp::Element fullscreen("fullscreen");
		video.LinkEndChild(&fullscreen);
		setAttr(fullscreen, "width", nVidWidth);
		setAttr(fullscreen, "height", nVidHeight);
		setAttr(fullscreen, "depth", nVidDepth);
		setAttr(fullscreen, "refresh", nVidRefresh);

		ticpp::Element adjust("adjust");
		video.LinkEndChild(&adjust);
		setAttr(adjust, "rotate-vertical", nVidRotationAdjust);

		ticpp::Element screen_size("screen-size");
		video.LinkEndChild(&screen_size);
		setAttr(screen_size, "window", nWindowSize);

		ticpp::Element window_position("window-position");
		video.LinkEndChild(&window_position);
		setAttr(window_position, "x", nWindowPosX);
		setAttr(window_position, "y", nWindowPosY);

		ticpp::Element stretch("stretch");
		video.LinkEndChild(&stretch);
		setAttr(stretch, "full-stretch", bVidFullStretch);
		setAttr(stretch, "correct-aspect", bVidCorrectAspect);

		ticpp::Element color("color");
		video.LinkEndChild(&color);
		setAttr(color, "enable", bcolorAdjust);
		setAttr(color, "contrast", color_contrast);
		setAttr(color, "brightness", color_brightness);
		setAttr(color, "gamma", color_gamma);
		setAttr(color, "grayscale", color_grayscale);
		setAttr(color, "invert", color_invert);

		ticpp::Element vsync("vsync");
		video.LinkEndChild(&vsync);
		setAttr(vsync, "enable", bVidVSync);

		ticpp::Element triple_buffer("triple-buffer");
		video.LinkEndChild(&triple_buffer);
		setAttr(triple_buffer, "enable", bVidTripleBuffer);

		// video render
		ticpp::Element render("render");
		video.LinkEndChild(&render);

		ticpp::Element render_driver("render-driver");
		render.LinkEndChild(&render_driver);
		setAttr(render_driver, "driver", nVidSelect);
		setAttr(render_driver, "adapter", nVidAdapter);

		ticpp::Element filter("filter");
		render.LinkEndChild(&filter);
		setAttr(filter, "linear", vidFilterLinear);
		setAttr(filter, "use-pixelfilter", vidUseFilter);
		setAttr(filter, "pixel-filter", nVidFilter);

		ticpp::Element option("option");
		render.LinkEndChild(&option);
		setAttr(option, "force-16bit", bVidForce16bit);
		setAttr(option, "hardware-vertex", vidHardwareVertex);
		setAttr(option, "motion-blur", vidMotionBlur);
		setAttr(option, "projection", nVid3DProjection);
		setAttr(option, "angel", fVidScreenAngle);
		setAttr(option, "curvature", fVidScreenCurvature);
		setAttr(option, "dxmanager", nVidDXTextureManager);

		setAttr(option, "x-offset", nXOffset);
		setAttr(option, "y-offset", nYOffset);
		setAttr(option, "x-scale",  nXScale);
		setAttr(option, "y-scale",  nYScale);

		// video others
		ticpp::Element monitor("monitor");
		video.LinkEndChild(&monitor);
		setAttr(monitor, "auto-aspect", autoVidScrnAspect);
		setAttr(monitor, "aspect-x", nVidScrnAspectX);
		setAttr(monitor, "aspect-y", nVidScrnAspectY);

		ticpp::Element frame("frame");
		video.LinkEndChild(&frame);
		setAttr(frame, "auto-frameskip", autoFrameSkip);
		setAttr(frame, "force-60hz", bForce60Hz);

		// audio
		ticpp::Element audio("audio");
		root.LinkEndChild(&audio);
		addTextNode(audio, "sound", audSelect);

		ticpp::Element device("device");
		audio.LinkEndChild(&device);
		setAttr(device, "ds", dsDevice);
		setAttr(device, "xa2", xa2Device);
		setAttr(device, "oal", oalDevice);

		ticpp::Element audio_set("setting");
		audio.LinkEndChild(&audio_set);
		setAttr(audio_set, "rate", nAudSampleRate);
		setAttr(audio_set, "frame", nAudSegCount);
		setAttr(audio_set, "dsp", nAudDSPModule);
		setAttr(audio_set, "pcm-interp", nInterpolation);
		setAttr(audio_set, "fm-interp", nFMInterpolation);
		setAttr(audio_set, "stereo-upmix", audStereoUpmixing);

		// gui
		ticpp::Element gui("gui");
		root.LinkEndChild(&gui);
		addTextNode(gui, "language", szLanguage);
		//addTextNode(gui, "gamelist", szTransGamelistFile);

		ticpp::Element chat("chat-font");
		gui.LinkEndChild(&chat);
		setAttr(chat, "min-size", nMinChatFontSize);
		setAttr(chat, "max-size", nMaxChatFontSize);

		ticpp::Element menu("menu");
		gui.LinkEndChild(&menu);
		setAttr(menu, "modeless", bModelessMenu);
		setAttr(menu, "style", menuNewStyle);

		ticpp::Element gui_misc("gui-misc");
		gui.LinkEndChild(&gui_misc);
		setAttr(gui_misc, "on-top", bShowOnTop);
		setAttr(gui_misc, "auto-fullscreen", bFullscreenOnStart);
		setAttr(gui_misc, "lastRom", nLastRom);
		setAttr(gui_misc, "lastFilter", nLastFilter);

		setAttr(gui_misc, "hideChildren", HideChildren);
		setAttr(gui_misc, "showThreeFourPlayerOnly", ThreeOrFourPlayerOnly);
		setAttr(gui_misc, "arcadeJoyStickSettings", ArcadeJoystick);

		// gui load game dialog
		ticpp::Element gamelist("gamelist-dlg");
		gui.LinkEndChild(&gamelist);
		setAttr(gamelist, "options", nLoadMenuShowX);
		//setAttr(gamelist, "drivers", nLoadDriverShowX);
		//setAttr(gamelist, "sys-sel", nSystemSel);
		//setAttr(gamelist, "tab-sel", nTabSel);
		//addTextNode(gamelist, "user-filter", szUserFilterStr);

		// gui ips
		ticpp::Element ips("ips");
		gui.LinkEndChild(&ips);
		setAttr(ips, "language", nPatchLang);
		setAttr(ips, "dependancy", bEnforceDep);

		//ticpp::Element skin("skin");
		//gui.LinkEndChild(&skin);
		//setAttr(skin, "use-placeholder", bVidUsePlaceholder);
		//setAttr(skin, "random", nRandomSkin);
		//addTextNode(skin, NULL, szPlaceHolder);

		// preferences
		ticpp::Element preference("preferences");
		root.LinkEndChild(&preference);

		ticpp::Element settings("settings");
		preference.LinkEndChild(&settings);
		setAttr(settings, "always-processkey", bAlwaysProcessKey);
		setAttr(settings, "auto-pause", bAutoPause);
		//setAttr(settings, "avi-audio", nAviIntAudio);
		//setAttr(settings, "use-gdip", bUseGdip);
		ticpp::Element fastforward("fastforward");
		preference.LinkEndChild(&fastforward);
		setAttr(fastforward, "speed", nFastSpeed);
		ticpp::Element thread("thread");
		preference.LinkEndChild(&thread);
		setAttr(thread, "priority", nAppThreadPriority);
		ticpp::Element autofire("autofire");
		preference.LinkEndChild(&autofire);
		setAttr(autofire, "enable", nAutofireEnabled);
		setAttr(autofire, "default-delay", autofireDefaultDelay);
		ticpp::Element macro("macro");
		preference.LinkEndChild(&macro);
		setAttr(macro, "enable", nInputMacroEnabled);

		// pref misc
		ticpp::Element pref_misc("misc");
		preference.LinkEndChild(&pref_misc);
		setAttr(pref_misc, "effect", nShowEffect);

		ticpp::Element controls("controls");
		preference.LinkEndChild(&controls);
		for (int i = 0; i < 4; i++) {
			sprintf(tempStr, "default%d", i);
			addTextNode(controls, tempStr, szPlayerDefaultIni[i]);
		}

		// paths
		ticpp::Element paths("paths");
		root.LinkEndChild(&paths);

		ticpp::Element rom_path("rom");
		paths.LinkEndChild(&rom_path);
		for (int i = 0; i < DIRS_MAX; i++) {
			addTextNode(rom_path, "path", szAppRomPaths[i]);
		}

		ticpp::Element misc_path("misc");
		paths.LinkEndChild(&misc_path);
		for (int i = PATH_PREVIEW; i < PATH_SUM; i++) {
			sprintf(tempStr, "path%d", i);
			addTextNode(misc_path, tempStr, szMiscPaths[i]);
		}

		// hotkeys
		ticpp::Element hotkeys("hotkeys");
		root.LinkEndChild(&hotkeys);

		/*for (int i = 0; !lastCustomKey(customKeys[i]); i++) {
			CustomKey& customkey = customKeys[i];

			ticpp::Element key(customkey.config_code);
			hotkeys.LinkEndChild(&key);
			setAttr(key, "key", customkey.key);
			setAttr(key, "mod", customkey.keymod);
		}*/

		// save file
		doc.SaveFile(configName, TIXML_ENCODING_UTF8);
	}
	catch (ticpp::Exception& ex) {
		return 1;
	}

	return 0;
}
示例#16
0
/* Main function
 */
int main (int argc, char *argv[]) 
{
    int i = 0;
    int run_mins = 0;
    machine_t machines[243];
    sensor_t sensor;

    /* Retrieve how long we want to monitor */
    if (argc > 1) {
        run_mins = strtol (argv[1], NULL, 10);
    }
    printf ("Monitoring set for %d minutes (0 = indefinite)\n", run_mins);

    /* Intialize machine data */
    int rc = machines_init (machines, &sensor);
    if (rc < 0) {
        printf ("Error: Machine initialization failed\n");
        return rc;
    }

    /* Create structs */
    mmdat_t *pshort_hist = (mmdat_t*) malloc (sizeof (mmdat_t));
    pshort_hist->head = NULL;
    pshort_hist->last = NULL;
    pshort_hist->size = 0;
    int wsize = 24 / PERIOD_LONG;
    mmdat_t *plong_hist = (mmdat_t *) malloc (sizeof (mmdat_t) * wsize);
    plong_hist->head = NULL;
    plong_hist->last = NULL;
    plong_hist->size = 0;

    int timeseed = 21;
    int *timestops = (int *)malloc (sizeof (int) * wsize);
    for (i = 0; i < wsize; i++) {
        timestops[i] = timeseed + i*PERIOD_LONG;
        if (timestops[i] >= 24) 
            timestops[i] = timestops[i] - 24;
    }

    opsum_t *summary = (opsum_t *) malloc (sizeof (opsum_t) * wsize);
    memset (summary, 0, sizeof (opsum_t) * wsize);
    for (i = 0; i < wsize; i++) {
        summary->avg_current = (double *)malloc (sizeof (double) * CMP_END);
        summary->avg_ratio = (double *)malloc (sizeof (double) * CMP_END);
        summary->variance = (double *)malloc (sizeof (double) * CMP_END);
    }


    /* Start monitor */
    rc = monitor (machines, &sensor, run_mins, pshort_hist, plong_hist, timestops, wsize, summary);
    if (rc < 0) {
        printf ("Failure while monitoring machines\n");
        return -1;
    }

    /* free memory */
    for (i = 0; i < 243; i++)
        free (machines[i].current_avgwindow);
    free (timestops);
    free (pshort_hist);
    free (plong_hist);   
    free (summary->avg_current);
    free (summary->avg_ratio);
    free (summary->variance);
    free (summary);

    /* Exit */
    printf ("Monitoring for stipulated time complete. Exiting...\n");
    
    return 0;
}
示例#17
0
 BOOL CALLBACK monitor_enum_proc(HMONITOR hmonitor, HDC hdc, LPRECT lprect, LPARAM lparam)
 {
     return (monitors.insert(monitor(hmonitor, hdc, lprect->right - lprect->left, lprect->bottom - lprect->top)) ? TRUE : FALSE);
 }
示例#18
0
bool
WaveReader::LoadFormatChunk()
{
  uint32_t fmtSize, rate, channels, frameSize, sampleFormat;
  char waveFormat[WAVE_FORMAT_CHUNK_SIZE];
  const char* p = waveFormat;

  // RIFF chunks are always word (two byte) aligned.
  NS_ABORT_IF_FALSE(mDecoder->GetResource()->Tell() % 2 == 0,
                    "LoadFormatChunk called with unaligned resource");

  // The "format" chunk may not directly follow the "riff" chunk, so skip
  // over any intermediate chunks.
  if (!ScanForwardUntil(FRMT_CHUNK_MAGIC, &fmtSize)) {
    return false;
  }

  if (!ReadAll(waveFormat, sizeof(waveFormat))) {
    return false;
  }

  PR_STATIC_ASSERT(sizeof(uint16_t) +
                   sizeof(uint16_t) +
                   sizeof(uint32_t) +
                   4 +
                   sizeof(uint16_t) +
                   sizeof(uint16_t) <= sizeof(waveFormat));
  if (ReadUint16LE(&p) != WAVE_FORMAT_ENCODING_PCM) {
    NS_WARNING("WAVE is not uncompressed PCM, compressed encodings are not supported");
    return false;
  }

  channels = ReadUint16LE(&p);
  rate = ReadUint32LE(&p);

  // Skip over average bytes per second field.
  p += 4;

  frameSize = ReadUint16LE(&p);

  sampleFormat = ReadUint16LE(&p);

  // PCM encoded WAVEs are not expected to have an extended "format" chunk,
  // but I have found WAVEs that have a extended "format" chunk with an
  // extension size of 0 bytes.  Be polite and handle this rather than
  // considering the file invalid.  This code skips any extension of the
  // "format" chunk.
  if (fmtSize > WAVE_FORMAT_CHUNK_SIZE) {
    char extLength[2];
    const char* p = extLength;

    if (!ReadAll(extLength, sizeof(extLength))) {
      return false;
    }

    PR_STATIC_ASSERT(sizeof(uint16_t) <= sizeof(extLength));
    uint16_t extra = ReadUint16LE(&p);
    if (fmtSize - (WAVE_FORMAT_CHUNK_SIZE + 2) != extra) {
      NS_WARNING("Invalid extended format chunk size");
      return false;
    }
    extra += extra % 2;

    if (extra > 0) {
      PR_STATIC_ASSERT(UINT16_MAX + (UINT16_MAX % 2) < UINT_MAX / sizeof(char));
      nsAutoArrayPtr<char> chunkExtension(new char[extra]);
      if (!ReadAll(chunkExtension.get(), extra)) {
        return false;
      }
    }
  }

  // RIFF chunks are always word (two byte) aligned.
  NS_ABORT_IF_FALSE(mDecoder->GetResource()->Tell() % 2 == 0,
                    "LoadFormatChunk left resource unaligned");

  // Make sure metadata is fairly sane.  The rate check is fairly arbitrary,
  // but the channels check is intentionally limited to mono or stereo
  // because that's what the audio backend currently supports.
  unsigned int actualFrameSize = sampleFormat == 8 ? 1 : 2 * channels;
  if (rate < 100 || rate > 96000 ||
      channels < 1 || channels > MAX_CHANNELS ||
      (frameSize != 1 && frameSize != 2 && frameSize != 4) ||
      (sampleFormat != 8 && sampleFormat != 16) ||
      frameSize != actualFrameSize) {
    NS_WARNING("Invalid WAVE metadata");
    return false;
  }

  ReentrantMonitorAutoEnter monitor(mDecoder->GetReentrantMonitor());
  mSampleRate = rate;
  mChannels = channels;
  mFrameSize = frameSize;
  if (sampleFormat == 8) {
    mSampleFormat = FORMAT_U8;
  } else {
    mSampleFormat = FORMAT_S16;
  }
  return true;
}
示例#19
0
static long process(struct timestampRecord *ptimestamp){

 const char * format=NULL; 
  ptimestamp->udf  = FALSE;
  ptimestamp->pact = TRUE;

  /* Device time here is the OS time appart from any epics
   * time stamp system */

  if (ptimestamp->tse==epicsTimeEventDeviceTime)
      epicsTimeFromTime_t(&ptimestamp->time,time(0));
  else
      recGblGetTimeStamp(ptimestamp);
  ptimestamp->rval=ptimestamp->time.secPastEpoch;

  if (ptimestamp->time.secPastEpoch==0)
  {
    sprintf(ptimestamp->val,"-NULL-");
  }
  else switch(ptimestamp->tst)
  {
  case timestampTST_YY_MM_DD_HH_MM_SS:
      format="%y/%m/%d %H:%M:%S";
    break;
  case timestampTST_MM_DD_YY_HH_MM_SS:
      format="%m/%d/%y %H:%M:%S";
    break;
  case timestampTST_MM_DD_HH_MM_SS_YY:
      format="%b %d %H:%M:%S %y" ;
    break;
  case timestampTST_MM_DD_HH_MM_SS:
      format="%b %d %H:%M:%S";
    break;
  case timestampTST_HH_MM_SS:
      format="%H:%M:%S";
    break;
  case timestampTST_HH_MM:
      format="%H:%M";
    break;
  case timestampTST_DD_MM_YY_HH_MM_SS:
      format="%d/%m/%y %H:%M:%S";
    break;
  case timestampTST_DD_MM_HH_MM_SS_YY:
      format="%d %b %H:%M:%S %y";
    break;
  case timestampTST_VMS:
      format="%d-%b-%Y %H:%M:%S";
    break;
  case timestampTST_MM_DD_YYYY:
      format="%b %d %Y %H:%M:%S.%03f";
    break;
  case timestampTST_MM_DD_YY:
      format="%m/%d/%y %H:%M:%S.%03f";
    break;
  default :  /* YY/MM/DD HH:MM:SS */
      format="%y/%m/%d %H:%M:%S";
    break;
  }
  if (format)
      epicsTimeToStrftime(ptimestamp->val,sizeof(ptimestamp->val),format,
	      &ptimestamp->time);
  /* check event list */
  monitor(ptimestamp);

  /* process the forward scan link record */
  recGblFwdLink(ptimestamp);
  ptimestamp->pact=FALSE;
  return(0);
}
示例#20
0
int Logic_DB_Request::process_load_player_data(Logic_Player_Detail *detail) {
	if (! detail) {
		MSG_USER("player_data == 0.");
		return -1;
	}

	if (detail->role_id <= 0) {
		POOL_MANAGER->push_player_data_pool(detail, 20);
		MSG_USER("player_data role_id:%d", detail->role_id);
		return -1;
	}

	Player_DB_View *player_db_view = 0;
	DB_View::ID_Player_View_Map::iterator db_player_find_it = monitor()->db_view()->id_player_view_map.find(detail->role_id);
	if (db_player_find_it == monitor()->db_view()->id_player_view_map.end()) {
		POOL_MANAGER->push_player_data_pool(detail, 21);
		MSG_USER("can not find db_view player:%ld", detail->role_id);
		return 0;
	}

	player_db_view = db_player_find_it->second;
	int cid = player_db_view->mode_value;

	// 处理登录过程中断线
	if (Player_DB_View::ACCOUNT_DOING_LOGOUT & player_db_view->account_mode) {
		POOL_MANAGER->push_player_data_pool(detail, 22);
		player_db_view->cancel_account_status(Player_DB_View::ACCOUNT_DOING_LOGOUT);
		MSG_USER("player login break, role:%ld, role_name:%s", detail->role_id, detail->base_detail.role_name.c_str());
		return 0;
	}

	// 没有此玩家数据, 可能数据库被删除
	if (detail->status == Logic_Player_Detail::ROLE_NOT_EXIST) {
		MSG_USER("can not find role:%ld", detail->role_id);
		POOL_MANAGER->push_player_data_pool(detail, 23);
		player_db_view->cancel_account_status(Player_DB_View::ACCOUNT_DOING_LOGIN);
		return monitor()->send_error_to_client(cid, 10000000, 10100001);
	}

	if (detail->status == Logic_Player_Detail::SUCCESS_LOADED) { /// [登录]数据加载成功
		Logic_Player *player = LOGIC_CLIENT_REQUEST->process_success_login(cid, *detail);
		if (!player) {
			monitor()->db_view()->login_cid_role_id_map.erase(cid);
			player_db_view->cancel_account_status(Player_DB_View::ACCOUNT_DOING_LOGIN);

			monitor()->send_error_to_client(cid, 10000000, 10100001);
			//POOL_MANAGER->push_player_data_pool(detail); 	player回收时已经回收detail
			MSG_USER("player login logic error, role:%ld, role_name:%s", player_db_view->role_id, player_db_view->role_name.c_str());
		} else {
			monitor()->db_view()->abnormal_account_add(player->role_id());
			MSG_DEBUG("player login logic success, role:%ld, role_name:%s", player_db_view->role_id, player_db_view->role_name.c_str());
		}
	} else {
		MSG_USER("unknow status = %d.", detail->status);
		POOL_MANAGER->push_player_data_pool(detail, 24);
		player_db_view->cancel_account_status(Player_DB_View::ACCOUNT_DOING_LOGIN);
		return monitor()->send_error_to_client(cid, 10000000, 10100001);
	}

	return 0;
}
示例#21
0
void DM_Server::putNget_async(const AMD_DistributedMap_putNgetPtr& png_cb,
        const string& word, const string& delta, const Ice::Current&) {
    IceUtil::Monitor<IceUtil::Mutex>::Lock monitor(_monitor_mutex);
    PNGJobPtr job = new PNGJob(png_cb, word, delta);
    _png_jobs.push_back(job);
    if (_num_consumers >= NUM_CONSUMERS) {
        //cerr << _num_consumers << " are working" << endl;
        int num_jobs_to_respond = _png_jobs.size();
        if (num_jobs_to_respond < QUE_FULL) {
            //cerr << "Queue is not full. Queuing up the job. Que Size: " << num_jobs_to_respond << endl;
            if (_waiting_thrds) { /*cerr << "Waking up waiting consumers" << endl;*/
                _monitor_mutex.notify();
            }
        } else {
            //cerr << "Queue is full. Acting as consumer" << endl;
            num_jobs_to_respond = min(CHUNK, (int) _png_jobs.size());
            vector<PNGJobPtr> my_png_jobs;
            for (int i = 0; i < num_jobs_to_respond; i++) {
                my_png_jobs.push_back(_png_jobs.front());
                _png_jobs.pop_front();
            }
            //cerr << "Cleared " << CHUNK << " jobs to process. Que Size: " << _png_jobs.size() << endl;
            monitor.release();
            for (int i = 0; i < num_jobs_to_respond; i++) {
                PNGJobPtr my_job = my_png_jobs[i];
                word_mutex_t::scoped_lock lock(*(_tc_table.get_lock(
                        my_job->word)), true);
                upd_counts(my_job->word, my_job->delta);
                string counts;
                get_counts(my_job->word, counts);
                lock.release();
                my_job->png_cb->ice_response(counts);
                //cerr << "Sent Response to job " << i << endl;
            }
            my_png_jobs.clear();
        }
    } else {
        //cerr << _num_consumers << " are working" << endl;
        ++_num_consumers;
        vector<PNGJobPtr> my_png_jobs;
        while (true) {
            int num_jobs_to_respond = min(CHUNK, (int) _png_jobs.size());
            for (int i = 0; i < num_jobs_to_respond; i++) {
                my_png_jobs.push_back(_png_jobs.front());
                _png_jobs.pop_front();
            }
            //cerr << "Cleared " << num_jobs_to_respond << " jobs to process. Que Size: " << _png_jobs.size() << endl;
            monitor.release();
            for (int i = 0; i < num_jobs_to_respond; i++) {
                PNGJobPtr my_job = my_png_jobs[i];
                word_mutex_t::scoped_lock lock(*(_tc_table.get_lock(
                        my_job->word)), true);
                upd_counts(my_job->word, my_job->delta);
                string counts;
                get_counts(my_job->word, counts);
                lock.release();
                my_job->png_cb->ice_response(counts);
                //cerr << "Sent Response to job " << i << endl;
            }
            my_png_jobs.clear();
            monitor.acquire();
            while (_png_jobs.empty()) {
                try {
                    ++_waiting_thrds;
                    //cerr << "Queue empty. " << _waiting_thrds << " are waiting including me" << endl;
                    _monitor_mutex.wait();
                    --_waiting_thrds;
                    //cerr << "Woke up, " << _waiting_thrds << " are waiting" << endl;
                } catch (const Ice::Exception& ex) {
                    --_waiting_thrds;
                    throw ex;
                }
            }
        }
    }
}
示例#22
0
 // The FrameType is sync to nsIStreamingProtocolController.h
 void SetFrameType(uint32_t aFrameType) {
   MonitorAutoLock monitor(mMonitor);
   mFrameType = mFrameType | aFrameType;
 }
示例#23
0
int main(int argc, char *argv[])
{
    int c = 0;
    FILE *fp = NULL;
    int long_opt_index = 0, i = 0, channel = 0, passive = 0, mode = 0;
    int source = INTERFACE, ret_val = EXIT_FAILURE;
    struct bpf_program bpf = { 0 };
    char *out_file = NULL, *last_optarg = NULL, *target = NULL, *bssid = NULL;
    char *short_options = "i:c:n:o:b:5sfuCDh";
    struct option long_options[] = {
        { "bssid", required_argument, NULL, 'b' },
        { "interface", required_argument, NULL, 'i' },
        { "channel", required_argument, NULL, 'c' },
        { "out-file", required_argument, NULL, 'o' },
        { "probes", required_argument, NULL, 'n' },
        { "daemonize", no_argument, NULL, 'D' },
        { "file", no_argument, NULL, 'f' },
        { "ignore-fcs", no_argument, NULL, 'C' },
        { "5ghz", no_argument, NULL, '5' },
        { "scan", no_argument, NULL, 's' },
        { "survey", no_argument, NULL, 'u' },
        { "help", no_argument, NULL, 'h' },
        { 0, 0, 0, 0 }
    };

    fprintf(stderr, "\nWash v%s WiFi Protected Setup Scan Tool\n", PACKAGE_VERSION);
    fprintf(stderr, "Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <*****@*****.**>\n\n");

    globule_init();
    sql_init();
    create_ap_table();
    set_auto_channel_select(0);
    set_wifi_band(BG_BAND);
    set_debug(INFO);
    set_validate_fcs(1);
    set_log_file(stdout);
    set_max_num_probes(DEFAULT_MAX_NUM_PROBES);

    while((c = getopt_long(argc, argv, short_options, long_options, &long_opt_index)) != -1)
    {
        switch(c)
        {
            case 'f':
                source = PCAP_FILE;
                break;
            case 'i':
                set_iface(optarg);
                break;
            case 'b':
                bssid = strdup(optarg);
                break;
            case 'c':
                channel = atoi(optarg);
                set_fixed_channel(1);
                break;
            case '5':
                set_wifi_band(AN_BAND);
                break;
            case 'n':
                set_max_num_probes(atoi(optarg));
                break;
            case 'o':
                out_file = strdup(optarg);
                break;
            case 's':
                mode = SCAN;
                break;
            case 'u':
                mode = SURVEY;
                break;
            case 'C':
                set_validate_fcs(0);
                break;
            case 'D':
                daemonize();
                break;
            default:
                usage(argv[0]);
                goto end;
        }

        /* Track the last optarg. This is used later when looping back through any specified pcap files. */
        if(optarg)
        {
            if(last_optarg)
            {
                free(last_optarg);
            }

            last_optarg = strdup(optarg);
        }
    }

    /* The interface value won't be set if capture files were specified; else, there should have been an interface specified */
    if(!get_iface() && source != PCAP_FILE)
    {
        usage(argv[0]);
        goto end;
    }
    else if(get_iface())
    {
        /* Get the MAC address of the specified interface */
        read_iface_mac();
    }

    if(get_iface() && source == PCAP_FILE)
    {
        cprintf(CRITICAL, "[X] ERROR: -i and -f options cannot be used together.\n");
        usage(argv[0]);
        goto end;
    }

    /* If we're reading from a file, be sure we don't try to transmit probe requests */
    if(source == PCAP_FILE)
    {
        passive = 1;
    }

    /* Open the output file, if any. If none, write to stdout. */
    if(out_file)
    {
        fp = fopen(out_file, "wb");
        if(!fp)
        {
            cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for writing\n", out_file);
            goto end;
        }

        set_log_file(fp);
    }

    /* 
     * Loop through all of the specified capture sources. If an interface was specified, this will only loop once and the
     * call to monitor() will block indefinitely. If capture files were specified, this will loop through each file specified
     * on the command line and monitor() will return after each file has been processed.
     */
    for(i=argc-1; i>0; i--)
    {
        /* If the source is a pcap file, get the file name from the command line */
        if(source == PCAP_FILE)
        {
            /* If we've gotten to the arguments, we're done */
            if((argv[i][0] == '-') ||
                    (last_optarg && (memcmp(argv[i], last_optarg, strlen(last_optarg)) == 0))
              )
            {
                break;
            }
            else
            {
                target = argv[i];
            }
        }
        /* Else, use the specified interface name */
        else
        {
            target = get_iface();
        }

        set_handle(capture_init(target));
        if(!get_handle())
        {
            cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for capturing\n", get_iface());
            goto end;
        }

        if(pcap_compile(get_handle(), &bpf, PACKET_FILTER, 0, 0) != 0)
        {
            cprintf(CRITICAL, "[X] ERROR: Failed to compile packet filter\n");
            goto end;
        }

        if(pcap_setfilter(get_handle(), &bpf) != 0)
        {
            cprintf(CRITICAL, "[X] ERROR: Failed to set packet filter\n");
            goto end;
        }

        /* Do it. */
        monitor(bssid, passive, source, channel, mode);
        printf("\n");
    }

    ret_val = EXIT_SUCCESS;

end:
    globule_deinit();
    sql_cleanup();
    if(bssid) free(bssid);
    if(out_file) free(out_file);
    if(wpsmon.fp) fclose(wpsmon.fp);
    return ret_val;
}
示例#24
0
/* When we perform a WriteBuffer, we check mIsStarted and aFrameType first.
 * These flags prevent "garbage" frames from being written into the buffer.
 *
 * After writing the data into the buffer, we check to see if we wrote over a
 * slot, and update mConsumerIdx if necessary.
 * This ensures that the decoder will get the "oldest" data available in the
 * buffer.
 *
 * If the incoming data is larger than one slot size (isMultipleSlots), we do
 * |mBufferSlotData[].mLength = BUFFER_SLOT_INVALID;| for other slots except the
 * first slot, in order to notify the reader that some slots are unavailable.
 *
 * If the incoming data is isMultipleSlots and crosses the end of
 * BUFFER_SLOT_NUM, returnToHead is set to true and the data will continue to
 * be written from head(index 0).
 *
 * MEDIASTREAM_FRAMETYPE_DISCONTINUITY currently is used when we are seeking.
 * */
void RtspTrackBuffer::WriteBuffer(const char *aFromBuffer, uint32_t aWriteCount,
                                  uint64_t aFrameTime, uint32_t aFrameType)
{
  MonitorAutoLock monitor(mMonitor);
  if (!mIsStarted) {
    RTSPMLOG("mIsStarted is false");
    return;
  }
  if (mTotalBufferSize < aWriteCount) {
    RTSPMLOG("mTotalBufferSize < aWriteCount, incoming data is too large");
    return;
  }
  // Checking the incoming data's frame type.
  // If we receive MEDIASTREAM_FRAMETYPE_DISCONTINUITY, clear the mFrameType
  // imply the RtspTrackBuffer is ready for receive data.
  if (aFrameType & MEDIASTREAM_FRAMETYPE_DISCONTINUITY) {
    mFrameType = mFrameType & (~MEDIASTREAM_FRAMETYPE_DISCONTINUITY);
    RTSPMLOG("Clear mFrameType");
    return;
  }
  // Checking current buffer frame type.
  // If the MEDIASTREAM_FRAMETYPE_DISCONTINUNITY bit is set, imply the
  // RtspTrackBuffer can't receive data now. So we drop the frame until we
  // receive MEDIASTREAM_FRAMETYPE_DISCONTINUNITY.
  if (mFrameType & MEDIASTREAM_FRAMETYPE_DISCONTINUITY) {
    RTSPMLOG("Return because the mFrameType is set");
    return;
  }
  // The flag is true if the incoming data is larger than one slot size.
  bool isMultipleSlots = false;
  // The flag is true if the incoming data is larger than remainder free slots
  bool returnToHead = false;
  // Calculate how many slots the incoming data needed.
  int32_t slots = 1;
  int32_t i;
  RTSPMLOG("WriteBuffer mTrackIdx %d mProducerIdx %d mConsumerIdx %d",
           mTrackIdx, mProducerIdx,mConsumerIdx);
  if (aWriteCount > mSlotSize) {
    isMultipleSlots = true;
    slots = (aWriteCount / mSlotSize) + 1;
  }
  if (isMultipleSlots &&
      (aWriteCount > (BUFFER_SLOT_NUM - mProducerIdx) * mSlotSize)) {
    returnToHead = true;
  }
  RTSPMLOG("slots %d isMultipleSlots %d returnToHead %d",
           slots, isMultipleSlots, returnToHead);
  if (returnToHead) {
    // Clear the rest index of mBufferSlotData[].mLength
    for (i = mProducerIdx; i < BUFFER_SLOT_NUM; ++i) {
      mBufferSlotData[i].mLength = BUFFER_SLOT_INVALID;
    }
    // We wrote one or more slots that the decode thread has not yet read.
    // So the mConsumerIdx returns to the head of slot buffer and moves forward
    // to the oldest slot.
    if (mProducerIdx <= mConsumerIdx && mConsumerIdx < mProducerIdx + slots) {
      mConsumerIdx = 0;
      for (i = mConsumerIdx; i < BUFFER_SLOT_NUM; ++i) {
        if (mBufferSlotData[i].mLength > 0) {
          mConsumerIdx = i;
          break;
        }
      }
    }
    mProducerIdx = 0;
  }

  memcpy(&(mRingBuffer[mSlotSize * mProducerIdx]), aFromBuffer, aWriteCount);

  if (mProducerIdx <= mConsumerIdx && mConsumerIdx < mProducerIdx + slots
      && mBufferSlotData[mConsumerIdx].mLength > 0) {
    // Wrote one or more slots that the decode thread has not yet read.
    RTSPMLOG("overwrite!! %d time %lld"
             ,mTrackIdx,mBufferSlotData[mConsumerIdx].mTime);
    mBufferSlotData[mProducerIdx].mLength = aWriteCount;
    mBufferSlotData[mProducerIdx].mTime = aFrameTime;
    // Clear the mBufferSlotDataLength except the start slot.
    if (isMultipleSlots) {
      for (i = mProducerIdx + 1; i < mProducerIdx + slots; ++i) {
        mBufferSlotData[i].mLength = BUFFER_SLOT_INVALID;
      }
    }
    mProducerIdx = (mProducerIdx + slots) % BUFFER_SLOT_NUM;
    // Move the mConsumerIdx forward to ensure that the decoder reads the
    // oldest data available.
    mConsumerIdx = mProducerIdx;
  } else {
    // Normal case, the writer doesn't take over the reader.
    mBufferSlotData[mProducerIdx].mLength = aWriteCount;
    mBufferSlotData[mProducerIdx].mTime = aFrameTime;
    // Clear the mBufferSlotData[].mLength except the start slot.
    if (isMultipleSlots) {
      for (i = mProducerIdx + 1; i < mProducerIdx + slots; ++i) {
        mBufferSlotData[i].mLength = BUFFER_SLOT_INVALID;
      }
    }
    mProducerIdx = (mProducerIdx + slots) % BUFFER_SLOT_NUM;
  }

  mMonitor.NotifyAll();
}
示例#25
0
nsresult
DOMStorageDBThread::InitDatabase()
{
  Telemetry::AutoTimer<Telemetry::LOCALDOMSTORAGE_INIT_DATABASE_MS> timer;

  nsresult rv;

  // Here we are on the worker thread. This opens the worker connection.
  MOZ_ASSERT(!NS_IsMainThread());

  rv = OpenDatabaseConnection();
  NS_ENSURE_SUCCESS(rv, rv);

  rv = TryJournalMode();
  NS_ENSURE_SUCCESS(rv, rv);

  // Create a read-only clone
  (void)mWorkerConnection->Clone(true, getter_AddRefs(mReaderConnection));
  NS_ENSURE_TRUE(mReaderConnection, NS_ERROR_FAILURE);

  mozStorageTransaction transaction(mWorkerConnection, false);

  // Ensure Gecko 1.9.1 storage table
  rv = mWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
         "CREATE TABLE IF NOT EXISTS webappsstore2 ("
         "scope TEXT, "
         "key TEXT, "
         "value TEXT, "
         "secure INTEGER, "
         "owner TEXT)"));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
        "CREATE UNIQUE INDEX IF NOT EXISTS scope_key_index"
        " ON webappsstore2(scope, key)"));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<mozIStorageFunction> function1(new nsReverseStringSQLFunction());
  NS_ENSURE_TRUE(function1, NS_ERROR_OUT_OF_MEMORY);

  rv = mWorkerConnection->CreateFunction(NS_LITERAL_CSTRING("REVERSESTRING"), 1, function1);
  NS_ENSURE_SUCCESS(rv, rv);

  bool exists;

  // Check if there is storage of Gecko 1.9.0 and if so, upgrade that storage
  // to actual webappsstore2 table and drop the obsolete table. First process
  // this newer table upgrade to priority potential duplicates from older
  // storage table.
  rv = mWorkerConnection->TableExists(NS_LITERAL_CSTRING("webappsstore"),
                                &exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (exists) {
    rv = mWorkerConnection->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("INSERT OR IGNORE INTO "
                         "webappsstore2(scope, key, value, secure, owner) "
                         "SELECT REVERSESTRING(domain) || '.:', key, value, secure, owner "
                         "FROM webappsstore"));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mWorkerConnection->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("DROP TABLE webappsstore"));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Check if there is storage of Gecko 1.8 and if so, upgrade that storage
  // to actual webappsstore2 table and drop the obsolete table. Potential
  // duplicates will be ignored.
  rv = mWorkerConnection->TableExists(NS_LITERAL_CSTRING("moz_webappsstore"),
                                &exists);
  NS_ENSURE_SUCCESS(rv, rv);

  if (exists) {
    rv = mWorkerConnection->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("INSERT OR IGNORE INTO "
                         "webappsstore2(scope, key, value, secure, owner) "
                         "SELECT REVERSESTRING(domain) || '.:', key, value, secure, domain "
                         "FROM moz_webappsstore"));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mWorkerConnection->ExecuteSimpleSQL(
      NS_LITERAL_CSTRING("DROP TABLE moz_webappsstore"));
    NS_ENSURE_SUCCESS(rv, rv);
  }

  rv = transaction.Commit();
  NS_ENSURE_SUCCESS(rv, rv);

  // Database open and all initiation operation are done.  Switching this flag
  // to true allow main thread to read directly from the database.
  // If we would allow this sooner, we would have opened a window where main thread
  // read might operate on a totaly broken and incosistent database.
  mDBReady = true;

  // List scopes having any stored data
  nsCOMPtr<mozIStorageStatement> stmt;
  rv = mWorkerConnection->CreateStatement(NS_LITERAL_CSTRING("SELECT DISTINCT scope FROM webappsstore2"),
                                    getter_AddRefs(stmt));
  NS_ENSURE_SUCCESS(rv, rv);
  mozStorageStatementScoper scope(stmt);

  while (NS_SUCCEEDED(rv = stmt->ExecuteStep(&exists)) && exists) {
    nsAutoCString foundScope;
    rv = stmt->GetUTF8String(0, foundScope);
    NS_ENSURE_SUCCESS(rv, rv);

    MonitorAutoLock monitor(mThreadObserver->GetMonitor());
    mScopesHavingData.PutEntry(foundScope);
  }

  return NS_OK;
}
示例#26
0
 void Start() {
   MonitorAutoLock monitor(mMonitor);
   mIsStarted = true;
   mFrameType = 0;
 }
static long process(acalcoutRecord *pcalc)
{
	rpvtStruct   *prpvt = (rpvtStruct *)pcalc->rpvt;
	long		i;
	double		*pnew, *pprev;

	if (aCalcoutRecordDebug) printf("acalcoutRecord(%s):process: pact=%d, cact=%d, dlya=%d\n",
		pcalc->name, pcalc->pact, pcalc->cact, pcalc->dlya);

	/* Make sure.  Autosave is capable of setting NUSE to an illegal value. */
	if ((pcalc->nuse < 0) || (pcalc->nuse > pcalc->nelm)) {
		pcalc->nuse = pcalc->nelm;
		db_post_events(pcalc,&pcalc->nuse, DBE_VALUE|DBE_LOG);
	}

	/* If we're getting processed, we can no longer put off allocating memory */
	if (pcalc->aval == NULL) pcalc->aval = (double *)calloc(pcalc->nelm, sizeof(double));
	if (pcalc->oav == NULL) pcalc->oav = (double *)calloc(pcalc->nelm, sizeof(double));

	if (!pcalc->pact) {
		pcalc->pact = TRUE;

		/* record scalar-field values so we can tell which ones aCalcPerform wrote to. */
		for (i=0, pnew=&pcalc->a, pprev=&pcalc->pa; i<MAX_FIELDS;  i++, pnew++, pprev++) {
			*pprev = *pnew;
		}

		/* if some links are CA, check connections */
		if (prpvt->caLinkStat != NO_CA_LINKS) checkLinks(pcalc);
		if (fetch_values(pcalc)==0) {
			long stat;

			if (aCalcoutRecordDebug >= 5) printf("acalcoutRecord(%s):process: queueing aCalcPerform\n", pcalc->name);

			pcalc->cact = 0;
			stat = doCalc(pcalc);
			if (stat) printf("%s:process: doCalc failed.\n", pcalc->name);
			if (stat == 0 && pcalc->cact == 1) {
				pcalc->pact = 1;
				/* we'll get processed again when the calculation is done */
				return(0);
			} else {
				if (afterCalc(pcalc) == ASYNC) return(0);
			}
		}
	} else { /* pact == TRUE */

		/* Who invoked us ? */
		if (pcalc->cact) {
			pcalc->cact = 0;
			if (afterCalc(pcalc) == ASYNC) return(0);
		} else if (pcalc->dlya) {
			/* callbackRequestProcessCallbackDelayed() called us */
			pcalc->dlya = 0;
			db_post_events(pcalc,&pcalc->dlya,DBE_VALUE);

			/* Must set pact 0 so that asynchronous device support works */
			pcalc->pact = 0;
			execOutput(pcalc);
			if (pcalc->pact) return(0);
			pcalc->pact = TRUE;
		} else {
			/* We must have been called by asynchronous device support */
			writeValue(pcalc);
		}
	}
	/*checkAlarms(pcalc); This is too late; IVOA might have vetoed output */
	recGblGetTimeStamp(pcalc);

	if (aCalcoutRecordDebug >= 5) {
		printf("acalcoutRecord(%s):process:calling monitor \n", pcalc->name);
	}

    monitor(pcalc);
    recGblFwdLink(pcalc);
    pcalc->pact = FALSE;

	if (aCalcoutRecordDebug >= 5) {
		printf("acalcoutRecord(%s):process-done\n", pcalc->name);
	}
	if (aCalcoutRecordDebug) printf("acalcoutRecord(%s):process: exit, pact==0\n",
		pcalc->name);
	return(0);
}
示例#28
0
 void Stop() {
   MonitorAutoLock monitor(mMonitor);
   mIsStarted = false;
 }
示例#29
0
/*------------------------------------------------------------------------
 *  comintr -- handle a serial line interrupt
 *------------------------------------------------------------------------
 */
int comintr()
{
    STATWORD		ps;
    unsigned char	iir, b;
    int			i, csr;

    disable(ps);
    
    for (i=0; i<Nserial; ++i) {
	csr = comtab[i].com_pdev->dvcsr;
	iir = inb(csr + UART_IIR);
	if (iir & UART_IIR_NO_INT)
	    continue;
	break;
    }

    if (i == Nserial) {
	restore(ps);
	return(OK);
    }

    switch (iir & UART_IIR_IID) {
    case UART_IIR_RLSI:
	b = inb(csr + UART_LSR);
#ifdef DEBUG
	kprintf("<LSR=%x>", b);
#endif
	if (b & UART_LSR_BI) {
	    (void) inb(csr + UART_RX);		/* discard it */

	    if (!(b & UART_LSR_OE)) { 		/* XXX */
		/* handles the BREAK signal here */
		kprintf("\nSerial line BREAK detected\n");
		monitor(csr);
	    }
	}
	break;
	    
    case UART_IIR_MSI:
	b = inb(csr + UART_MSR);
#ifdef DEBUG
	kprintf("(MSR=%x)", b);
#endif
	break;
	    
    case UART_IIR_RDI:		/* received a char */
	b = inb(csr + UART_RX);
#ifdef DEBUG
	kprintf("{RX=%x}", b);
#endif
	if (b == 0) {		/* XXX maybe a BREAK */
	    /* handles the BREAK signal here */
	    kprintf("\nSerial line BREAK detected.\n");
	    monitor(csr);
	}
	else
	    comiin(&comtab[i], b);
	break;
	    
    case UART_IIR_THRI:
	b = inb(csr + UART_LSR);
#ifdef DEBUG
	kprintf("[LSR=%x]", b);
#endif
	if (b & UART_LSR_THRE && comtab[i].com_count) {
	    comwstrt(&comtab[i], csr);
	}
	break;

    default:
	kprintf("comintr: unknown int: iir = 0x%x\n", iir);	
    }
    
    restore(ps);
    return(OK);
}
示例#30
0
文件: main.c 项目: sirianray/lblc
int main(int argc, char *argv[]){
	MPI_Init(&argc, &argv);
    MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &shmcomm);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

	double t_begin, zeta0;
	int i, j, k, ii, id, id1;

	t_begin = MPI_Wtime();		// record the begining CPU time
	
	read_param();
	lattice_vec();
	allocate();
	p_allocate();

	if (flow_on!=0) {
		build_stream();
	}

	if (Q_on!=0 || phi_on!=0) {
		build_neighbor();		
	}

	init_surf();
	add_patch();
	p_init();
	p_iden();
    p_set_neighb();
	init();

    zeta0 = zeta;
    zeta  = 0.;

	if (flow_on!=0) cal_fequ(f);	
	if (Q_on!=0) cal_dQ();
    if (phi_on!=0) cal_mu();

	if ((Q_on!=0 || phi_on!=0) && flow_on!=0 && newrun_on!=0) {
		while( (qconverge==0 || pconverge==0) && t_current<n_pre_evol) {
			t_current++;
            if (Q_on!=0) {
		        for (ii=0; ii<n_evol_Q; ii++) {
                    cal_dQ();
                    evol_Q();
                }
            }
            if (phi_on!=0) {
		        for (ii=0; ii<n_evol_phi; ii++) {
                    cal_mu();
                    evol_phi();
                }
            }
			if (t_current%t_print==0) monitor();
		}
		e_tot     =-1;
		k_eng     =-1;
		qconverge = 0;
        pconverge = 0;
		uconverge = 0;
		t_current =-1;
	}

	if (Q_on!=0 && flow_on!=0) {
		cal_W();
		cal_stress2();
		cal_sigma_p();
	}
    if (phi_on!=0 && flow_on!=0) {
        cal_mu();
        cal_stress_phi(Q_on);
    }
    MPI_Barrier(MPI_COMM_WORLD);

	output1(1,'z',Nx/2,Ny/2);
	output3(1);
	if(myid==0) printf("Q initialized\n");
	MPI_Barrier(MPI_COMM_WORLD);

    zeta = zeta0;

	if (t_current%t_print==0) monitor();
	while (t_current<t_max && uconverge*qconverge*pconverge==0) {
		e_toto=e_tot;
		if (Q_on!=0 && qconverge==0) {
			if (flow_on!=0 && uconverge==0) cal_W();
			for (ii=0; ii<n_evol_Q; ii++) {
				cal_dQ();
				evol_Q();
			}			
		}

        if (phi_on!=0 && pconverge==0) {
			if (flow_on!=0 && uconverge==0) cal_W();
			for (ii=0; ii<n_evol_phi; ii++) {
                cal_mu();
                evol_phi();
			}			
        }

		if (flow_on!=0 && uconverge==0) {
			if (Q_on!=0 && qconverge==0) {
				cal_stress2();
				cal_sigma_p();
			}
			if (phi_on!=0 && pconverge==0) {
                cal_mu();
				cal_stress_phi(Q_on);
			}
			evol_f(f,f2);
		}

		if (Q_on!=0 && qconverge==0) {
			if (flow_on!=0 && uconverge==0) cal_W();
			for (ii=0; ii<n_evol_Q; ii++) {
				cal_dQ();
				evol_Q();
			}			
		}

        if (phi_on!=0 && pconverge==0) {
			if (flow_on!=0 && uconverge==0) cal_W();
			for (ii=0; ii<n_evol_phi; ii++) {
                cal_mu();
                evol_phi();
			}			
        }

		if (flow_on!=0 && uconverge==0) {
			if (Q_on!=0 && qconverge==0) {
				cal_stress2();
				cal_sigma_p();
			}
			if (phi_on!=0 && pconverge==0) {
                cal_mu();
				cal_stress_phi(Q_on);
			}
			evol_f(f2,f);
		}
		
		if (t_current%t_print==0) monitor();
		if (t_current%t_write==0 && t_current>0) {
			output1(0,'z',Nx/2,Ny/2);
			output3(0);
	        write_restart();
			fflush(stdout);
		}
		t_current++;
	}
	
	
	output_time(t_begin);
	output1(0,'z',Nx/2,Ny/2);
//	output3(1);
	
	write_restart();

	p_deallocate();
	deallocate();

	return 0;
}