static void
impl_MateComponent_Canvas_Component_draw (PortableServer_Servant        servant,
				   const MateComponent_Canvas_State    *state,
				   const CORBA_char             *drawable_id,
				   CORBA_short                   x,
				   CORBA_short                   y,
				   CORBA_short                   width,
				   CORBA_short                   height,
				   CORBA_Environment            *ev)
{
	Gcc *gcc = GCC (matecomponent_object_from_servant (servant));
	MateCanvasItem *item = MATE_CANVAS_ITEM (gcc->priv->item);
	GdkPixmap *pix;
	
	gdk_flush ();
	pix = gdk_pixmap_foreign_new_for_display
		(gtk_widget_get_display (GTK_WIDGET (item->canvas)),
		 matecomponent_control_x11_from_window_id (drawable_id));

	if (pix == NULL){
		g_warning ("Invalid window id passed='%s'", drawable_id);
		return;
	}

	restore_state (item, state);
	ICLASS (item)->draw (item, pix, x, y, width, height);

	my_gdk_pixmap_foreign_release (pix);
	gdk_flush ();
}
Ejemplo n.º 2
0
/*
 * Reset emulator
 */
static void do_reset_machine (int hardreset)
{
#ifdef SAVESTATE
    if (savestate_state == STATE_RESTORE)
	restore_state (savestate_fname);
    else if (savestate_state == STATE_REWIND)
	savestate_rewind ();
#endif
    /* following three lines must not be reordered or
     * fastram state restore breaks
     */
    reset_all_systems ();
    customreset ();
    m68k_reset ();
    if (hardreset) {
	memset (chipmemory, 0, allocated_chipmem);
	write_log ("chipmem cleared\n");
    }
#ifdef SAVESTATE
    /* We may have been restoring state, but we're done now.  */
    if (savestate_state == STATE_RESTORE || savestate_state == STATE_REWIND)
    {
	map_overlay (1);
	fill_prefetch_slow (&regs); /* compatibility with old state saves */
    }
    savestate_restore_finish ();
#endif

    fill_prefetch_slow (&regs);
    if (currprefs.produce_sound == 0)
	eventtab[ev_audio].active = 0;
    handle_active_events ();

    inputdevice_updateconfig (&currprefs);
}
Ejemplo n.º 3
0
uint16_t phy_send(uint8_t* data, uint16_t length, uint16_t *timestamp) {
	uint8_t tx_length, *tx_data;

	if (length > PHY_MAX_LENGTH) {
		return 0;
	}
	state = TX;

	tx_data = data;
	tx_length = length;

	// Take semaphore
	xSemaphoreTake(spi_mutex, portMAX_DELAY);

	// Stop radio and flush TX FIFO
	cc1101_cmd_idle();
	cc1101_cmd_flush_tx();

	// Configure gdo2 to TX FIFO
	cc1101_cfg_gdo2(CC1101_GDOx_TX_FIFO);

	// Send length byte and first set
	length = tx_length > 63 ? 63 : tx_length;

	// Start TX
	cc1101_cmd_tx();

	cc1101_fifo_put(&tx_length, 1);
	cc1101_fifo_put(tx_data, length);
	tx_data += length;
	tx_length -= length;

	// Loop for sending everything
	while (tx_length != 0) {
		if (cc1101_gdo2_read() == 0) {
			length = tx_length > 31 ? 31 : tx_length;
			cc1101_fifo_put(tx_data, length);
			tx_data += length;
			tx_length -= length;
		}
	}

	// Wait while there are bytes in TX FIFO and EOP has not happened
	while (cc1101_status_txbytes() || cc1101_gdo0_read()) {
		nop();
	}

	// Release semaphore
	xSemaphoreGive(spi_mutex);

	// Set timestamp if required
	if (timestamp != 0x0) {
		*timestamp = sync_word_time;
	}

	restore_state();
	return 1;
}
Ejemplo n.º 4
0
int main(void) {
  init();
  self_test();
  restore_state();
  while(1) {
    key_press(&key1_lock, &PINA, KEY1, minus);
    key_press(&key2_lock, &PINB, KEY2, plus);
    render_leds();
  };
};
Ejemplo n.º 5
0
void handle_restore_state(void* ctx,
                          void* tag,
                          dr_mcontext_t* mcontext,
                          bool restore_memory,
                          bool app_code_consistent) {
#ifdef TRACE_DEBUG
  dr_fprintf(STDERR, "debug: restoring state for tag=%p..\n", tag);
#endif

  restore_state(ctx, mcontext, find_tag_or_die(tag));
}
Ejemplo n.º 6
0
static void
gitg_window_parser_finished(GtkBuildable *buildable, GtkBuilder *builder)
{
	if (parent_iface.parser_finished)
		parent_iface.parser_finished(buildable, builder);

	// Store widgets
	GitgWindow *window = GITG_WINDOW(buildable);
	
	window->priv->vpaned_main = GTK_WIDGET(gtk_builder_get_object(builder, "vpaned_main"));
	window->priv->hpaned_commit = GTK_WIDGET(gtk_builder_get_object(builder, "hpaned_commit"));
	window->priv->vpaned_commit = GTK_WIDGET(gtk_builder_get_object(builder, "vpaned_commit"));
	
	window->priv->notebook_main = GTK_NOTEBOOK(gtk_builder_get_object(builder, "notebook_main"));
	window->priv->tree_view = GTK_TREE_VIEW(gtk_builder_get_object(builder, "tree_view_rv"));
	window->priv->statusbar = GTK_STATUSBAR(gtk_builder_get_object(builder, "statusbar"));
	window->priv->revision_view = GITG_REVISION_VIEW(gtk_builder_get_object(builder, "revision_view"));
	window->priv->revision_tree_view = GITG_REVISION_TREE_VIEW(gtk_builder_get_object(builder, "revision_tree_view"));
	window->priv->commit_view = GITG_COMMIT_VIEW(gtk_builder_get_object(builder, "hpaned_commit"));

	restore_state(window);

	window->priv->edit_group = GTK_ACTION_GROUP(gtk_builder_get_object(builder, "action_group_menu_edit"));

	GtkTreeViewColumn *col = GTK_TREE_VIEW_COLUMN(gtk_builder_get_object(builder, "rv_column_subject"));
	
	window->priv->renderer_path = GITG_CELL_RENDERER_PATH(gtk_builder_get_object(builder, "rv_renderer_subject"));
	gtk_tree_view_column_set_cell_data_func(col, GTK_CELL_RENDERER(window->priv->renderer_path), (GtkTreeCellDataFunc)on_renderer_path, window, NULL);
	
	GtkRecentFilter *filter = gtk_recent_filter_new();
	gtk_recent_filter_add_group(filter, "gitg");

	GtkRecentChooser *chooser = GTK_RECENT_CHOOSER(gtk_builder_get_object(builder, "RecentOpenAction"));
	gtk_recent_chooser_add_filter(chooser, filter);

	// Intialize branches
	build_branches_combo(window, builder);

	// Create search entry
	build_search_entry(window, builder);
	
	gtk_builder_connect_signals(builder, window);

	// Connect signals
	GtkTreeSelection *selection = gtk_tree_view_get_selection(window->priv->tree_view);
	g_signal_connect(selection, "changed", G_CALLBACK(on_selection_changed), window);
	g_signal_connect(window->priv->revision_view, "parent-activated", G_CALLBACK(on_parent_activated), window);
	
	g_signal_connect(window->priv->tree_view, "motion-notify-event", G_CALLBACK(on_tree_view_motion), window);
	g_signal_connect(window->priv->tree_view, "button-release-event", G_CALLBACK(on_tree_view_button_release), window);
}
Ejemplo n.º 7
0
//*******************************************************************
// QBtConfigApps                                       CONSTRUCTOR
//*******************************************************************
QBtConfigApps::QBtConfigApps( QWidget* in_parent ) : QWidget( in_parent )
, console_default_ ( new QRadioButton( tr( DEFAULT_CONSOLE ) ) )
, console_other_   ( new QRadioButton( tr( OTHER_CONSOLE   ) ) )
, console_command_ ( new QLineEdit )
, diff_default_    ( new QRadioButton( tr( DEFAULT_DIFF ) ) )
, diff_other_      ( new QRadioButton( tr( OTHER_DIFF   ) ) )
, diff_command_    ( new QLineEdit )
{
   console_default_->setChecked( true  );
   console_other_  ->setChecked( false );
   console_command_->setEnabled( false );
   diff_default_   ->setChecked( true  );
   diff_other_     ->setChecked( false );
   diff_command_   ->setEnabled( false );

   
   // console
   QHBoxLayout* const other_console_layout = new QHBoxLayout;
   other_console_layout->addWidget( console_other_ );
   other_console_layout->addWidget( console_command_ );

   QGroupBox* const console_gbox = new QGroupBox( tr( CONSOLE ) );  
   QVBoxLayout* const console_layout = new QVBoxLayout( console_gbox );
   console_layout->addWidget( console_default_ );
   console_layout->addLayout( other_console_layout );

   // diff
   QHBoxLayout* const other_diff_layout = new QHBoxLayout;
   other_diff_layout->addWidget( diff_other_   );
   other_diff_layout->addWidget( diff_command_ );

   QGroupBox* const diff_gbox = new QGroupBox( tr( DIFF ) );  
   QVBoxLayout* const diff_layout = new QVBoxLayout( diff_gbox );
   diff_layout->addWidget( diff_default_ );
   diff_layout->addLayout( other_diff_layout );


   // main layout
   QVBoxLayout* const main_layout = new QVBoxLayout;
   main_layout->addWidget( console_gbox );
   main_layout->addWidget( diff_gbox );
   main_layout->addStretch();
   setLayout( main_layout );

   connect( console_other_, SIGNAL( toggled( bool ) ),
            this          , SLOT  ( other_console_selected( bool ) ) );
   connect( diff_other_   , SIGNAL( toggled( bool ) ),
            this          , SLOT  ( other_diff_selected( bool ) ) );

   restore_state();
}
static void
impl_MateComponent_Canvas_Component_bounds (PortableServer_Servant     servant,
				     const MateComponent_Canvas_State *state,
				     CORBA_double              *x1,
				     CORBA_double              *x2,
				     CORBA_double              *y1,
				     CORBA_double              *y2,
				     CORBA_Environment         *ev)
{
	Gcc *gcc = GCC (matecomponent_object_from_servant (servant));
	MateCanvasItem *item = MATE_CANVAS_ITEM (gcc->priv->item);

	restore_state (item, state);
	ICLASS (item)->bounds (item, x1, y1, x2, y2);
}
Ejemplo n.º 9
0
        contact_list_dialog::contact_list_dialog(
                const std::string& title, 
                us::user_service_ptr service,
                QWidget* parent) :
            QDialog{parent},
            _service{service}
        {
            REQUIRE(service);

            //create tabs
            auto layout = new QVBoxLayout{this};
            setLayout(layout);
            auto tabs = new QTabWidget{this};
            tabs->setDocumentMode(true);
            layout->addWidget(tabs);

            auto* contacts_tab = new QWidget;
            auto* contacts_layout = new QGridLayout{contacts_tab};

            auto* intro_tab = new QWidget;
            auto* intro_layout = new QGridLayout{intro_tab};

            auto* greeters_tab = new QWidget;
            auto* greeters_layout = new QGridLayout{greeters_tab};
            if(_service->user().greeters().empty())
            {
                tabs->addTab(greeters_tab, tr("locators"));
                tabs->addTab(contacts_tab, tr("people"));
            }
            else
            {
                tabs->addTab(contacts_tab, tr("people"));
                tabs->addTab(greeters_tab, tr("locators"));
            }

            tabs->addTab(intro_tab, tr("introductions"));
            if(!_service->user().introductions().empty())
                tabs->tabBar()->setTabTextColor(2, QColor{"red"});

            init_greeters_tab(greeters_tab, greeters_layout);
            init_contacts_tab(contacts_tab, contacts_layout);
            init_intro_tab(intro_tab, intro_layout);

            setWindowTitle(tr(title.c_str()));
            restore_state();

            INVARIANT(_list);
        }
Ejemplo n.º 10
0
static MonoException*
continuation_restore (MonoContinuation *cont, int state)
{
	MonoLMF **lmf_addr = mono_get_lmf_addr ();
	MonoContinuationRestore restore_state = mono_tasklets_arch_restore ();

	if (!cont->domain || !cont->return_sp)
		return mono_get_exception_argument ("cont", "Continuation not initialized");
	if (cont->domain != mono_domain_get () || cont->thread_id != GetCurrentThreadId ())
		return mono_get_exception_argument ("cont", "Continuation from another thread or domain");

	/*g_print ("restore: %p, state: %d\n", cont, state);*/
	*lmf_addr = cont->lmf;
	restore_state (cont, state, lmf_addr);
	g_assert_not_reached ();
}
/*
 * Receives events from the container end, decodes it into a synthetic
 * GdkEvent and forwards this to the CanvasItem
 */
static CORBA_boolean
impl_MateComponent_Canvas_Component_event (PortableServer_Servant     servant,
				    const MateComponent_Canvas_State *state,
				    const MateComponent_Gdk_Event    *mate_event,
				    CORBA_Environment         *ev)
{
	Gcc *gcc = GCC (matecomponent_object_from_servant (servant));
	MateCanvasItem *item = MATE_CANVAS_ITEM (gcc->priv->item);
	GdkEvent *gdk_event = gdk_event_new(GDK_NOTHING);
	CORBA_boolean retval = FALSE;
        EmitLater *data;

	restore_state (item, state);
        
        gdk_event->any.window = item->canvas->layout.bin_window;
        g_object_ref(gdk_event->any.window);

	MateComponent_Gdk_Event_to_GdkEvent (mate_event, gdk_event);

        /*
         * Problem: When dealing with multiple canvas component's within the
         * same process it is possible to get to this point when one of the
         * pseudo-canvas's is inside its idle loop.  This is normally not a
         * problem unless an event from one component can trigger a request for
         * an update on another component.
         *
         * Solution: If any component is in do_update, set up an idle_handler
         * and send the event later. If the event is sent later, the client will
         * get a false return value.  Normally this value is used to determine
         * whether or not to propagate the event up the canvas group tree.
         */

        if (!do_update_flag) {
                retval = handle_event(GTK_WIDGET(item->canvas), gdk_event);
                gdk_event_free(gdk_event);
        }
        else {
                data = g_new0(EmitLater, 1);
                data->arg1 = (gpointer)item->canvas;
                data->arg2 = (gpointer)gdk_event;
                /* has a higher priority then do_update*/
                g_idle_add_full(GDK_PRIORITY_REDRAW-10,
                                (GSourceFunc)handle_event_later, data, NULL);
        }

	return retval;
}
Ejemplo n.º 12
0
void
gcc_genericize (tree fndecl)
{
  FILE *dump_orig;
  int local_dump_flags;
  struct cgraph_node *cgn;

  /* Dump the C-specific tree IR.  */
  dump_orig = gcc_dump_begin (TDI_original, &local_dump_flags);

  /*
	  if(dump_orig)
	{
		printf("should start dumping original tree.\n");
	}else{
		printf("no dumping original tree flag.\n");
	}
	*/

  if (dump_orig)
	{
	  fprintf (dump_orig, "\n;; Function %s",
		   lang_hooks.decl_printable_name (fndecl, 2));

	  astTreeBuilder->addFunctionName(lang_hooks.decl_printable_name (fndecl, 2));

	  fprintf (dump_orig, " (%s)\n",
		   (!DECL_ASSEMBLER_NAME_SET_P (fndecl) ? "null"
		: IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (fndecl))));
	  fprintf (dump_orig, ";; enabled by -%s\n", dump_flag_name (TDI_original));
	  fprintf (dump_orig, "\n");

	  //if (local_dump_flags & TDF_RAW)
	gcc_dump_node (DECL_SAVED_TREE (fndecl),
		   TDF_SLIM | local_dump_flags, dump_orig);
 //     else
//	print_c_tree (dump_orig, DECL_SAVED_TREE (fndecl));
	  fprintf (dump_orig, "\n");
	  restore_state();
	  gcc_dump_end (TDI_original, dump_orig);
	}

  /* Dump all nested functions now.  */
  cgn = cgraph_node (fndecl);
  for (cgn = cgn->nested; cgn ; cgn = cgn->next_nested)
	gcc_genericize (cgn->decl);
}
Ejemplo n.º 13
0
EAPI int
elm_main(int argc, char **argv)
{
    //const char *theme;

    //int ret;

    //get users home dir
    const char *name = "HOME";
    sprintf(home_dir, "%s", getenv(name));

    //adjust finger size
    elm_config_finger_size_set(55);

    //paroli theme fix - not required anymore
    //theme = "tasks";
    //elm_theme_overlay_add(theme);

    //set up win
    win = elm_win_add(NULL, "tasks", ELM_WIN_BASIC);
    elm_win_title_set(win, "Tasks");
    evas_object_smart_callback_add(win, "delete,request", my_win_del, NULL);

    //open database
    open_database();

    // show the window
    create_gui(win);
    evas_object_show(win);

    //restore state
    restore_state();

    occupy_cpu();

    elm_run();
    //clean up stuff
    //clean_up();
    ecore_main_loop_quit();
    elm_shutdown();

    return 0;
}
Ejemplo n.º 14
0
// XXX: use exceptions on Windows
dr_signal_action_t handle_signal(void* ctx, dr_siginfo_t* siginfo) {
  dr_fprintf(STDERR, "info: caught signal %u\n", (unsigned int)siginfo->sig);
  if(siginfo->sig == SIGSEGV) {
    struct trace_buffer_t* tb;
    struct tag_info_t* tag_info;

#ifdef TRACE_DEBUG
    dr_fprintf(STDERR,
               "debug: this is SIGSEGV and faulting address is " PFX "\n",
               siginfo->access_address);
#endif
    if(siginfo->raw_mcontext == NULL) {
      dr_fprintf(STDERR, "fatal: raw_mcontext missing\n");
      dr_exit_process(1);
    }
#ifdef TRACE_DEBUG
    dr_fprintf(STDERR, "debug: offending instruction is\n");
    disassemble(ctx, siginfo->raw_mcontext->xip, STDERR);
#endif

    tag_info = find_tag_or_die(siginfo->fault_fragment_info.tag);
    if(is_guard_page_access(siginfo->raw_mcontext,
                            tag_info,
                            siginfo->fault_fragment_info.cache_start_pc)) {
#ifdef TRACE_DEBUG
      dr_fprintf(STDERR, "debug: this is guard page access\n");
#endif

      // Flush.
      tb = dr_get_tls_field(siginfo->drcontext);
      tb_flush(tb);
      tb_tlv(tb, TYPE_TRACE);

      // Restart instrumentation.
      siginfo->raw_mcontext->xip = siginfo->fault_fragment_info.cache_start_pc +
                                   tag_info->instr_info.first_offset;
      restore_state(ctx, siginfo->raw_mcontext, tag_info);
      return DR_SIGNAL_SUPPRESS;
    }
  }
  return DR_SIGNAL_DELIVER;
}
Ejemplo n.º 15
0
void ui_mega_process()
{
	int mx, my, mz;
	unsigned char k;
	
	event_process();

	switch( Record )
	{
	case 0:
		mouse_get_delta( &mx, &my, &mz );
		Mouse.new_dx = mx;
		Mouse.new_dy = my;
		Mouse.new_buttons = mouse_get_btns();
		last_keypress = key_inkey();

		if ( Mouse.new_buttons || last_keypress || Mouse.new_dx || Mouse.new_dy )	{
			last_event = timer_query();
		}

		break;
	case 1:

		if (ui_event_counter==0 )
		{
			EventBuffer[ui_event_counter].frame = 0;
			EventBuffer[ui_event_counter].type = 7;
			EventBuffer[ui_event_counter].data = ui_number_of_events;
			ui_event_counter++;
		}


		if (ui_event_counter==1 && (RecordFlags & UI_RECORD_MOUSE) )
		{
			Mouse.new_buttons = 0;
			EventBuffer[ui_event_counter].frame = FrameCount;
			EventBuffer[ui_event_counter].type = 6;
			EventBuffer[ui_event_counter].data = ((Mouse.y & 0xFFFF) << 16) | (Mouse.x & 0xFFFF);
			ui_event_counter++;
		}

		mouse_get_delta( &mx, &my, &mz );
		MouseDX = mx;
		MouseDY = my;
		MouseButtons = mouse_get_btns();

		Mouse.new_dx = MouseDX;
		Mouse.new_dy = MouseDY;

		if ((MouseDX != 0 || MouseDY != 0)  && (RecordFlags & UI_RECORD_MOUSE)  )
		{
			if (ui_event_counter < ui_number_of_events-1 )
			{
				EventBuffer[ui_event_counter].frame = FrameCount;
				EventBuffer[ui_event_counter].type = 1;
				EventBuffer[ui_event_counter].data = ((MouseDY & 0xFFFF) << 16) | (MouseDX & 0xFFFF);
				ui_event_counter++;
			} else {
				Record = 0;
			}

		}

		if ( (MouseButtons != Mouse.new_buttons) && (RecordFlags & UI_RECORD_MOUSE) )
		{
			Mouse.new_buttons = MouseButtons;

			if (ui_event_counter < ui_number_of_events-1 )
			{
				EventBuffer[ui_event_counter].frame = FrameCount;
				EventBuffer[ui_event_counter].type = 2;
				EventBuffer[ui_event_counter].data = MouseButtons;
				ui_event_counter++;
			} else {
				Record = 0;
			}

		}


		if ( keyd_last_pressed && (RecordFlags & UI_RECORD_KEYS) )
		{
			_disable();
			k = keyd_last_pressed;
			keyd_last_pressed= 0;
			_enable();

			if (ui_event_counter < ui_number_of_events-1 )
			{
				EventBuffer[ui_event_counter].frame = FrameCount;
				EventBuffer[ui_event_counter].type = 3;
				EventBuffer[ui_event_counter].data = k;
				ui_event_counter++;
			} else {
				Record = 0;
			}

		}

		if ( keyd_last_released && (RecordFlags & UI_RECORD_KEYS) )
		{
			_disable();
			k = keyd_last_released;
			keyd_last_released= 0;
			_enable();

			if (ui_event_counter < ui_number_of_events-1 )
			{
				EventBuffer[ui_event_counter].frame = FrameCount;
				EventBuffer[ui_event_counter].type = 4;
				EventBuffer[ui_event_counter].data = k;
				ui_event_counter++;
			} else {
				Record = 0;
			}
		}

		last_keypress = key_inkey();

		if (last_keypress == KEY_F12 )
		{
			ui_number_of_events = ui_event_counter;
			last_keypress = 0;
			Record = 0;
			break;
		}

		if ((last_keypress != 0) && (RecordFlags & UI_RECORD_KEYS) )
		{
			if (ui_event_counter < ui_number_of_events-1 )
			{
				EventBuffer[ui_event_counter].frame = FrameCount;
				EventBuffer[ui_event_counter].type = 5;
				EventBuffer[ui_event_counter].data = last_keypress;
				ui_event_counter++;
			} else {
				Record = 0;
			}
		}

		FrameCount++;

		break;
	case 2:
	case 3:
		Mouse.new_dx = 0;
		Mouse.new_dy = 0;
		Mouse.new_buttons = 0;
		last_keypress = 0;

		if ( keyd_last_pressed ) {
			_disable();			
			k = keyd_last_pressed;
			keyd_last_pressed = 0;
			_disable();
			SavedState[k] = 1;
		}

		if ( keyd_last_released ) 
		{
			_disable();			
			k = keyd_last_released;
			keyd_last_released = 0;
			_disable();
			SavedState[k] = 0;
		}
		
		if (key_inkey() == KEY_F12 )
		{
			restore_state();
			Record = 0;
			break;
		}

		if (EventBuffer==NULL) {
			restore_state();
			Record = 0;
			break;
		}

		while( (ui_event_counter < ui_number_of_events) && (EventBuffer[ui_event_counter].frame <= FrameCount) )
		{
			switch ( EventBuffer[ui_event_counter].type )
			{
			case 1:     // Mouse moved
				Mouse.new_dx = EventBuffer[ui_event_counter].data & 0xFFFF;
				Mouse.new_dy = (EventBuffer[ui_event_counter].data >> 16) & 0xFFFF;
				break;
			case 2:     // Mouse buttons changed
				Mouse.new_buttons = EventBuffer[ui_event_counter].data;
				break;
			case 3:     // Key moved down
				keyd_pressed[ EventBuffer[ui_event_counter].data ] = 1;
				break;
			case 4:     // Key moved up
				keyd_pressed[ EventBuffer[ui_event_counter].data ] = 0;
				break;
			case 5:     // Key pressed
				last_keypress = EventBuffer[ui_event_counter].data;
				break;
			case 6:     // Initial Mouse X position
				Mouse.x = EventBuffer[ui_event_counter].data & 0xFFFF;
				Mouse.y = (EventBuffer[ui_event_counter].data >> 16) & 0xFFFF;
				break;
			case 7:
				break;
			}
			ui_event_counter++;
			if (ui_event_counter >= ui_number_of_events )
			{
				Record = 0;
				restore_state();
				//( 0, "Done playing %d events.\n", ui_number_of_events );
			}
		}

		switch (Record)
		{
		case 2:
			{
				int next_frame;
			
				if ( ui_event_counter < ui_number_of_events )
				{
					next_frame = EventBuffer[ui_event_counter].frame;
					
					if ( (FrameCount+PlaybackSpeed) < next_frame )
						FrameCount = next_frame - PlaybackSpeed;
					else
						FrameCount++;
				} else {
				 	FrameCount++;
				}	
			}
			break;

		case 3:			
 			if ( ui_event_counter < ui_number_of_events ) 
				FrameCount = EventBuffer[ui_event_counter].frame;
			else 		
				FrameCount++;
			break;
		default:		
			FrameCount++;
		}
	}

	ui_mouse_process();

}
Ejemplo n.º 16
0
int main(int argc, char *argv[]) {
        _cleanup_udev_unref_ struct udev *udev = NULL;
        _cleanup_udev_device_unref_ struct udev_device *device = NULL;
        _cleanup_free_ char *saved = NULL, *escaped_name = NULL, *escaped_path_id = NULL;
        const char *name, *path_id;
        int r;

        if (argc != 3) {
                log_error("This program requires two arguments.");
                return EXIT_FAILURE;
        }

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        umask(0022);

        r = mkdir_p("/var/lib/systemd/rfkill", 0755);
        if (r < 0) {
                log_error("Failed to create rfkill directory: %s", strerror(-r));
                return EXIT_FAILURE;
        }

        udev = udev_new();
        if (!udev) {
                log_oom();
                return EXIT_FAILURE;
        }

        errno = 0;
        device = udev_device_new_from_subsystem_sysname(udev, "rfkill", argv[2]);
        if (!device) {
                if (errno != 0)
                        log_error("Failed to get rfkill device '%s': %m", argv[2]);
                else
                        log_oom();

                return EXIT_FAILURE;
        }

        name = udev_device_get_sysattr_value(device, "name");
        if (!name) {
                log_error("rfkill device has no name?");
                return EXIT_FAILURE;
        }

        escaped_name = cescape(name);
        if (!escaped_name) {
                log_oom();
                return EXIT_FAILURE;
        }

        path_id = udev_device_get_property_value(device, "ID_PATH");
        if (path_id) {
                escaped_path_id = cescape(path_id);
                if (!escaped_path_id) {
                        log_oom();
                        return EXIT_FAILURE;
                }

                saved = strjoin("/var/lib/systemd/rfkill/", escaped_path_id, ":", escaped_name, NULL);
        } else
                saved = strjoin("/var/lib/systemd/rfkill/", escaped_name, NULL);

        if (!saved) {
                log_oom();
                return EXIT_FAILURE;
        }

        if (streq(argv[1], "load") && restore_state()) {
                _cleanup_free_ char *value = NULL;

                r = read_one_line_file(saved, &value);
                if (r < 0) {

                        if (r == -ENOENT)
                                return EXIT_SUCCESS;

                        log_error("Failed to read %s: %s", saved, strerror(-r));
                        return EXIT_FAILURE;
                }

                r = udev_device_set_sysattr_value(device, "soft", value);
                if (r < 0) {
                        log_error("Failed to write system attribute: %s", strerror(-r));
                        return EXIT_FAILURE;
                }

        } else if (streq(argv[1], "save")) {
                const char *value;

                value = udev_device_get_sysattr_value(device, "soft");
                if (!value) {
                        log_error("Failed to read system attribute: %s", strerror(-r));
                        return EXIT_FAILURE;
                }

                r = write_string_file(saved, value);
                if (r < 0) {
                        log_error("Failed to write %s: %s", saved, strerror(-r));
                        return EXIT_FAILURE;
                }

        } else {
                log_error("Unknown verb %s.", argv[1]);
                return EXIT_FAILURE;
        }

        return EXIT_SUCCESS;
}
Ejemplo n.º 17
0
int cmd_merge(int argc, const char **argv, const char *prefix)
{
	unsigned char result_tree[20];
	unsigned char stash[20];
	unsigned char head_sha1[20];
	struct commit *head_commit;
	struct strbuf buf = STRBUF_INIT;
	const char *head_arg;
	int flag, i, ret = 0, head_subsumed;
	int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
	struct commit_list *common = NULL;
	const char *best_strategy = NULL, *wt_strategy = NULL;
	struct commit_list *remoteheads, *p;
	void *branch_to_free;

	if (argc == 2 && !strcmp(argv[1], "-h"))
		usage_with_options(builtin_merge_usage, builtin_merge_options);

	/*
	 * Check if we are _not_ on a detached HEAD, i.e. if there is a
	 * current branch.
	 */
	branch = branch_to_free = resolve_refdup("HEAD", head_sha1, 0, &flag);
	if (branch && !prefixcmp(branch, "refs/heads/"))
		branch += 11;
	if (!branch || is_null_sha1(head_sha1))
		head_commit = NULL;
	else
		head_commit = lookup_commit_or_die(head_sha1, "HEAD");

	git_config(git_merge_config, NULL);

	if (branch_mergeoptions)
		parse_branch_merge_options(branch_mergeoptions);
	argc = parse_options(argc, argv, prefix, builtin_merge_options,
			builtin_merge_usage, 0);
	if (shortlog_len < 0)
		shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;

	if (verbosity < 0 && show_progress == -1)
		show_progress = 0;

	if (abort_current_merge) {
		int nargc = 2;
		const char *nargv[] = {"reset", "--merge", NULL};

		if (!file_exists(git_path("MERGE_HEAD")))
			die(_("There is no merge to abort (MERGE_HEAD missing)."));

		/* Invoke 'git reset --merge' */
		ret = cmd_reset(nargc, nargv, prefix);
		goto done;
	}

	if (read_cache_unmerged())
		die_resolve_conflict("merge");

	if (file_exists(git_path("MERGE_HEAD"))) {
		/*
		 * There is no unmerged entry, don't advise 'git
		 * add/rm <file>', just 'git commit'.
		 */
		if (advice_resolve_conflict)
			die(_("You have not concluded your merge (MERGE_HEAD exists).\n"
				  "Please, commit your changes before you can merge."));
		else
			die(_("You have not concluded your merge (MERGE_HEAD exists)."));
	}
	if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
		if (advice_resolve_conflict)
			die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n"
			    "Please, commit your changes before you can merge."));
		else
			die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists)."));
	}
	resolve_undo_clear();

	if (verbosity < 0)
		show_diffstat = 0;

	if (squash) {
		if (!allow_fast_forward)
			die(_("You cannot combine --squash with --no-ff."));
		option_commit = 0;
	}

	if (!allow_fast_forward && fast_forward_only)
		die(_("You cannot combine --no-ff with --ff-only."));

	if (!abort_current_merge) {
		if (!argc) {
			if (default_to_upstream)
				argc = setup_with_upstream(&argv);
			else
				die(_("No commit specified and merge.defaultToUpstream not set."));
		} else if (argc == 1 && !strcmp(argv[0], "-"))
			argv[0] = "@{-1}";
	}
	if (!argc)
		usage_with_options(builtin_merge_usage,
			builtin_merge_options);

	/*
	 * This could be traditional "merge <msg> HEAD <commit>..."  and
	 * the way we can tell it is to see if the second token is HEAD,
	 * but some people might have misused the interface and used a
	 * committish that is the same as HEAD there instead.
	 * Traditional format never would have "-m" so it is an
	 * additional safety measure to check for it.
	 */

	if (!have_message && head_commit &&
	    is_old_style_invocation(argc, argv, head_commit->object.sha1)) {
		strbuf_addstr(&merge_msg, argv[0]);
		head_arg = argv[1];
		argv += 2;
		argc -= 2;
		remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
	} else if (!head_commit) {
		struct commit *remote_head;
		/*
		 * If the merged head is a valid one there is no reason
		 * to forbid "git merge" into a branch yet to be born.
		 * We do the same for "git pull".
		 */
		if (argc != 1)
			die(_("Can merge only exactly one commit into "
				"empty head"));
		if (squash)
			die(_("Squash commit into empty head not supported yet"));
		if (!allow_fast_forward)
			die(_("Non-fast-forward commit does not make sense into "
			    "an empty head"));
		remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
		remote_head = remoteheads->item;
		if (!remote_head)
			die(_("%s - not something we can merge"), argv[0]);
		read_empty(remote_head->object.sha1, 0);
		update_ref("initial pull", "HEAD", remote_head->object.sha1,
			   NULL, 0, DIE_ON_ERR);
		goto done;
	} else {
		struct strbuf merge_names = STRBUF_INIT;

		/* We are invoked directly as the first-class UI. */
		head_arg = "HEAD";

		/*
		 * All the rest are the commits being merged; prepare
		 * the standard merge summary message to be appended
		 * to the given message.
		 */
		remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv);
		for (p = remoteheads; p; p = p->next)
			merge_name(merge_remote_util(p->item)->name, &merge_names);

		if (!have_message || shortlog_len) {
			struct fmt_merge_msg_opts opts;
			memset(&opts, 0, sizeof(opts));
			opts.add_title = !have_message;
			opts.shortlog_len = shortlog_len;

			fmt_merge_msg(&merge_names, &merge_msg, &opts);
			if (merge_msg.len)
				strbuf_setlen(&merge_msg, merge_msg.len - 1);
		}
	}

	if (!head_commit || !argc)
		usage_with_options(builtin_merge_usage,
			builtin_merge_options);

	strbuf_addstr(&buf, "merge");
	for (p = remoteheads; p; p = p->next)
		strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name);
	setenv("GIT_REFLOG_ACTION", buf.buf, 0);
	strbuf_reset(&buf);

	for (p = remoteheads; p; p = p->next) {
		struct commit *commit = p->item;
		strbuf_addf(&buf, "GITHEAD_%s",
			    sha1_to_hex(commit->object.sha1));
		setenv(buf.buf, merge_remote_util(commit)->name, 1);
		strbuf_reset(&buf);
		if (!fast_forward_only &&
		    merge_remote_util(commit) &&
		    merge_remote_util(commit)->obj &&
		    merge_remote_util(commit)->obj->type == OBJ_TAG)
			allow_fast_forward = 0;
	}

	if (option_edit < 0)
		option_edit = default_edit_option();

	if (!use_strategies) {
		if (!remoteheads)
			; /* already up-to-date */
		else if (!remoteheads->next)
			add_strategies(pull_twohead, DEFAULT_TWOHEAD);
		else
			add_strategies(pull_octopus, DEFAULT_OCTOPUS);
	}

	for (i = 0; i < use_strategies_nr; i++) {
		if (use_strategies[i]->attr & NO_FAST_FORWARD)
			allow_fast_forward = 0;
		if (use_strategies[i]->attr & NO_TRIVIAL)
			allow_trivial = 0;
	}

	if (!remoteheads)
		; /* already up-to-date */
	else if (!remoteheads->next)
		common = get_merge_bases(head_commit, remoteheads->item, 1);
	else {
		struct commit_list *list = remoteheads;
		commit_list_insert(head_commit, &list);
		common = get_octopus_merge_bases(list);
		free(list);
	}

	update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1,
		   NULL, 0, DIE_ON_ERR);

	if (remoteheads && !common)
		; /* No common ancestors found. We need a real merge. */
	else if (!remoteheads ||
		 (!remoteheads->next && !common->next &&
		  common->item == remoteheads->item)) {
		/*
		 * If head can reach all the merge then we are up to date.
		 * but first the most common case of merging one remote.
		 */
		finish_up_to_date("Already up-to-date.");
		goto done;
	} else if (allow_fast_forward && !remoteheads->next &&
			!common->next &&
			!hashcmp(common->item->object.sha1, head_commit->object.sha1)) {
		/* Again the most common case of merging one remote. */
		struct strbuf msg = STRBUF_INIT;
		struct commit *commit;
		char hex[41];

		strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV));

		if (verbosity >= 0)
			printf(_("Updating %s..%s\n"),
				hex,
				find_unique_abbrev(remoteheads->item->object.sha1,
				DEFAULT_ABBREV));
		strbuf_addstr(&msg, "Fast-forward");
		if (have_message)
			strbuf_addstr(&msg,
				" (no commit created; -m option ignored)");
		commit = remoteheads->item;
		if (!commit) {
			ret = 1;
			goto done;
		}

		if (checkout_fast_forward(head_commit->object.sha1,
					  commit->object.sha1,
					  overwrite_ignore)) {
			ret = 1;
			goto done;
		}

		finish(head_commit, remoteheads, commit->object.sha1, msg.buf);
		drop_save();
		goto done;
	} else if (!remoteheads->next && common->next)
		;
		/*
		 * We are not doing octopus and not fast-forward.  Need
		 * a real merge.
		 */
	else if (!remoteheads->next && !common->next && option_commit) {
		/*
		 * We are not doing octopus, not fast-forward, and have
		 * only one common.
		 */
		refresh_cache(REFRESH_QUIET);
		if (allow_trivial && !fast_forward_only) {
			/* See if it is really trivial. */
			git_committer_info(IDENT_STRICT);
			printf(_("Trying really trivial in-index merge...\n"));
			if (!read_tree_trivial(common->item->object.sha1,
					       head_commit->object.sha1,
					       remoteheads->item->object.sha1)) {
				ret = merge_trivial(head_commit, remoteheads);
				goto done;
			}
			printf(_("Nope.\n"));
		}
	} else {
		/*
		 * An octopus.  If we can reach all the remote we are up
		 * to date.
		 */
		int up_to_date = 1;
		struct commit_list *j;

		for (j = remoteheads; j; j = j->next) {
			struct commit_list *common_one;

			/*
			 * Here we *have* to calculate the individual
			 * merge_bases again, otherwise "git merge HEAD^
			 * HEAD^^" would be missed.
			 */
			common_one = get_merge_bases(head_commit, j->item, 1);
			if (hashcmp(common_one->item->object.sha1,
				j->item->object.sha1)) {
				up_to_date = 0;
				break;
			}
		}
		if (up_to_date) {
			finish_up_to_date("Already up-to-date. Yeeah!");
			goto done;
		}
	}

	if (fast_forward_only)
		die(_("Not possible to fast-forward, aborting."));

	/* We are going to make a new commit. */
	git_committer_info(IDENT_STRICT);

	/*
	 * At this point, we need a real merge.  No matter what strategy
	 * we use, it would operate on the index, possibly affecting the
	 * working tree, and when resolved cleanly, have the desired
	 * tree in the index -- this means that the index must be in
	 * sync with the head commit.  The strategies are responsible
	 * to ensure this.
	 */
	if (use_strategies_nr == 1 ||
	    /*
	     * Stash away the local changes so that we can try more than one.
	     */
	    save_state(stash))
		hashcpy(stash, null_sha1);

	for (i = 0; i < use_strategies_nr; i++) {
		int ret;
		if (i) {
			printf(_("Rewinding the tree to pristine...\n"));
			restore_state(head_commit->object.sha1, stash);
		}
		if (use_strategies_nr != 1)
			printf(_("Trying merge strategy %s...\n"),
				use_strategies[i]->name);
		/*
		 * Remember which strategy left the state in the working
		 * tree.
		 */
		wt_strategy = use_strategies[i]->name;

		ret = try_merge_strategy(use_strategies[i]->name,
					 common, remoteheads,
					 head_commit, head_arg);
		if (!option_commit && !ret) {
			merge_was_ok = 1;
			/*
			 * This is necessary here just to avoid writing
			 * the tree, but later we will *not* exit with
			 * status code 1 because merge_was_ok is set.
			 */
			ret = 1;
		}

		if (ret) {
			/*
			 * The backend exits with 1 when conflicts are
			 * left to be resolved, with 2 when it does not
			 * handle the given merge at all.
			 */
			if (ret == 1) {
				int cnt = evaluate_result();

				if (best_cnt <= 0 || cnt <= best_cnt) {
					best_strategy = use_strategies[i]->name;
					best_cnt = cnt;
				}
			}
			if (merge_was_ok)
				break;
			else
				continue;
		}

		/* Automerge succeeded. */
		write_tree_trivial(result_tree);
		automerge_was_ok = 1;
		break;
	}

	/*
	 * If we have a resulting tree, that means the strategy module
	 * auto resolved the merge cleanly.
	 */
	if (automerge_was_ok) {
		ret = finish_automerge(head_commit, head_subsumed,
				       common, remoteheads,
				       result_tree, wt_strategy);
		goto done;
	}

	/*
	 * Pick the result from the best strategy and have the user fix
	 * it up.
	 */
	if (!best_strategy) {
		restore_state(head_commit->object.sha1, stash);
		if (use_strategies_nr > 1)
			fprintf(stderr,
				_("No merge strategy handled the merge.\n"));
		else
			fprintf(stderr, _("Merge with strategy %s failed.\n"),
				use_strategies[0]->name);
		ret = 2;
		goto done;
	} else if (best_strategy == wt_strategy)
		; /* We already have its result in the working tree. */
	else {
		printf(_("Rewinding the tree to pristine...\n"));
		restore_state(head_commit->object.sha1, stash);
		printf(_("Using the %s to prepare resolving by hand.\n"),
			best_strategy);
		try_merge_strategy(best_strategy, common, remoteheads,
				   head_commit, head_arg);
	}

	if (squash)
		finish(head_commit, remoteheads, NULL, NULL);
	else
		write_merge_state(remoteheads);

	if (merge_was_ok)
		fprintf(stderr, _("Automatic merge went well; "
			"stopped before committing as requested\n"));
	else
		ret = suggest_conflicts(option_renormalize);

done:
	free(branch_to_free);
	return ret;
}
Ejemplo n.º 18
0
void vlm5030_device::device_post_load()
{
	restore_state();
}
Ejemplo n.º 19
0
int main(void)
{

	DDRB |= (1 << PWM_PIN);	 // Set PWM pin to output, enable main channel
	TCCR0A = FAST; // Set timer to do PWM for correct output pin and set prescaler timing
	TCCR0B = 0x01; // Set timer to do PWM for correct output pin and set prescaler timing

	restore_state(); // Read config values and saved state

	count_modes(); // Enable the current mode group
	 // check button press time, unless we're in group selection mode
	if (mode_idx != GROUP_SELECT_MODE) {
		if ( we_did_a_fast_press() ) { // sram hasn't decayed yet, must have been a short press
			increment_fast_presses();
			next_mode(); // Will handle wrap arounds
		} else { // Long press, keep the same mode
			reset_fast_presses();
			if( !memory_is_enabled() ) {mode_idx = 0;}  // if memory is turned off, set mode_idx to 0
		}
	}
	save_mode();

	// Turn features on or off as needed
	#ifdef VOLTAGE_MON
	ADC_on();
	#else
	ADC_off();
	#endif

	uint8_t output;
	uint8_t i = 0;
	uint16_t ticks = 0;
#ifdef TURBO_RAMP_DOWN
	uint8_t adj_output = 255;
#endif
	
#ifdef VOLTAGE_MON
	uint8_t lowbatt_cnt = 0;
	uint8_t voltage;
	ADCSRA |= (1 << ADSC); // Make sure voltage reading is running for later
#endif

	if(mode_idx > num_modes) { output = mode_idx; }  // special modes, override output
	else { output = modes[mode_idx]; }
	
	while(1) {
		if (fast_presses[0] >= 12) {  // Config mode if 12 or more fast presses
			_delay_s();	   // wait for user to stop fast-pressing button
			reset_fast_presses(); // exit this mode after one use

			toggle_mode(GROUP_SELECT_MODE, 1); // Enter the mode group selection mode?
			toggle_options((options ^ 0b00010000), 2); // memory
			toggle_options((options ^ 0b00100000), 3); // hidden blinkies
			toggle_options((options ^ 0b01000000), 4); // hidden battcheck
			toggle_options((options ^ 0b10000000), 5); // turbo timer
			toggle_options(DEFAULTS, 6); // reset to defaults
		}
		else if (output == STROBE) { // 10Hz tactical strobe
			for(i=0;i<8;i++) {
				set_level(RAMP_SIZE);
				_delay_ms(33);
				set_output(0);
				_delay_ms(67);
			}
		}
		else if (output == BEACON) {
			set_level(RAMP_SIZE);
			_delay_ms(10);
			set_output(0);
			_delay_s(); _delay_s();
		}
		else if (output == SOS) {  // dot = 1 unit, dash = 3 units, space betwen parts of a letter = 1 unit, space between letters = 3 units
			#define SOS_SPEED 200  // these speeds aren't perfect, but they'll work for the [never] times they'll actually get used
			blink(3, SOS_SPEED); // 200 on, 400 off, 200 on, 400 off, 200 on, 400 off
			_delay_ms(SOS_SPEED);  // wait for 200
			blink(3, SOS_SPEED*5/2);  // 500 on, 1000 off, 500 on, 1000 off, 500 on, 1000 off (techically too long on that last off beat, but oh well)
			blink(3, SOS_SPEED);  // 200 on, 400 off, 200 on, 400 off, 200 on, 400 off
			_delay_s(); _delay_s();
		}
		else if (output == BATT_CHECK) {
			 blink(battcheck(), BLINK_SPEED/4);
			 _delay_s(); _delay_s();
		}
		else if (output == GROUP_SELECT_MODE) {
			mode_idx = 0; // exit this mode after one use

			for(i=0; i<NUM_MODEGROUPS; i++) {
				toggle_options(((options & 0b11110000) | i), i+1);
			}
			_delay_s();
		}
		else {
			if ((output == TURBO) && ( ttimer_is_enabled() ) && (ticks > (TURBO_MINUTES * TICKS_PER_MINUTE))) {
	#ifdef TURBO_RAMP_DOWN
				if (adj_output > TURBO_LOWER) { adj_output = adj_output - 2; }
				set_output(adj_output);
	#else
				set_output(TURBO_LOWER);
	#endif
			}
			else {
				ticks ++; // count ticks for turbo timer
				set_level(output);
			}

			_delay_ms(500);  // Otherwise, just sleep.

		}
		reset_fast_presses();
#ifdef VOLTAGE_MON
		if (ADCSRA & (1 << ADIF)) {  // if a voltage reading is ready
			voltage = ADCH;  // get the waiting value
	
			if (voltage < ADC_LOW) { // See if voltage is lower than what we were looking for
				lowbatt_cnt ++;
			} else {
				lowbatt_cnt = 0;
			}
			
			if (lowbatt_cnt >= 8) {  // See if it's been low for a while, and maybe step down
				//set_output(0);  _delay_ms(100); // blink on step-down:

				if (output > RAMP_SIZE) {  // blinky modes 
					output = RAMP_SIZE / 2; // step down from blinky modes to medium
				} else if (output > 1) {  // regular solid mode
					output = output - 1; // step down from solid modes somewhat gradually
				} else { // Already at the lowest mode
					set_output(0); // Turn off the light
					set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Power down as many components as possible
					sleep_mode();
				}
				set_level(output);
				lowbatt_cnt = 0;
				_delay_s(); // Wait before lowering the level again
			}

			ADCSRA |= (1 << ADSC); // Make sure conversion is running for next time through
		}
#endif  // ifdef VOLTAGE_MON
	}
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
	/* Don't bother checking for privilege if they only want usage() */
	if (argc < 2)
		goto usage;
	
	vbetool_init();
	
	if (!strcmp(argv[1], "vbestate")) {
		/* VBE save/restore tends to break when done underneath X */
		int err = check_console();

		if (err) {
			return err;
		}

		if (!strcmp(argv[2], "save")) {
			save_state();
		} else if (!strcmp(argv[2], "restore")) {
			restore_state();
		} else {
			goto usage;
		}
	} else if (!strcmp(argv[1], "dpms")) {
		if (!strcmp(argv[2], "on")) {
			return do_blank(DPMS_STATE_ON);
		} else if (!strcmp(argv[2], "suspend")) {
			return do_blank(DPMS_STATE_SUSPEND);
		} else if (!strcmp(argv[2], "standby")) {
			return do_blank(DPMS_STATE_STANDBY);
		} else if (!strcmp(argv[2], "off")) {
			return do_blank(DPMS_STATE_OFF);
		} else if (!strcmp(argv[2], "reduced")) {
			return do_blank(DPMS_STATE_LOW);
		} else {
			goto usage;
		}
	} else if (!strcmp(argv[1], "vbemode")) {
		if (!strcmp(argv[2], "set")) {
			return do_set_mode(atoi(argv[3]),0);
		} else if (!strcmp(argv[2], "get")) {
			return do_get_mode();
		} else {
			goto usage;
		}
	} else if (!strcmp(argv[1], "vgamode")) {
		if (!strcmp(argv[2], "set")) {
			return do_set_mode(atoi(argv[3]),1);
		} else {
			return do_set_mode(atoi(argv[2]),1);
		}
	} else if (!strcmp(argv[1], "post")) {
		/* Again, we don't really want to do this while X is in 
		   control */
		int err = check_console();

		if (err) {
			return err;
		}

		return do_post();
	} else if (!strcmp(argv[1], "vgastate")) {
		if (!strcmp(argv[2], "on")) {
			return enable_vga();
		} else {
			return disable_vga();
		}
	} else if (!strcmp(argv[1], "vbefp")) {
		if (!strcmp(argv[2], "id") || !strcmp(argv[2], "panelid")) {
			return do_get_panel_id(0);
		} else if (!strcmp(argv[2], "panelsize")) {
			return do_get_panel_id(1);
		} else if (!strcmp(argv[2], "getbrightness")) {
			return do_get_panel_brightness();
		} else if (!strcmp(argv[2], "setbrightness")) {
			return do_set_panel_brightness(atoi(argv[3]));
		} else if (!strcmp(argv[2], "invert")) {
			return do_invert_panel();
		} else {
			return 1;
		}
	} else {
	      usage:
		fprintf(stderr,
			"%s: Usage %s [[vbestate save|restore]|[vbemode set|get]|[vgamode]|[dpms on|off|standby|suspend|reduced]|[post]|[vgastate on|off]|[vbefp panelid|panelsize|getbrightness|setbrightness|invert]]\n",
			argv[0], argv[0]);
		return 1;
	}

	return 0;
}
int main(int argc, char **argv)
{
  pthread_t *decryption_threads;
  char *filename;
  int fd, i, ret, c;
  struct stat file_stats;

  setlocale(LC_ALL, "");
  OpenSSL_add_all_algorithms();

  /* Get options and parameters */
  opterr = 0;
  while((c = getopt(argc, argv, "1aB:b:c:d:e:f:hL:l:M:m:Nns:t:v:w:")) != -1)
    switch(c)
    {
    case '1':
      only_one_password = 1;
      break;

    case 'a':
      list_algorithms();
      exit(EXIT_FAILURE);
      break;

    case 'B':
      binary = optarg;
      break;

    case 'b':
      prefix_len = mbstowcs(NULL, optarg, 0);
      if(prefix_len == (unsigned int) -1)
      {
        fprintf(stderr, "Error: invalid character in prefix.\n\n");
        exit(EXIT_FAILURE);
      }
      prefix = (wchar_t *) calloc(prefix_len + 1, sizeof(wchar_t));
      if(prefix == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(prefix, optarg, prefix_len + 1);
      break;

    case 'c':
      cipher = EVP_get_cipherbyname(optarg);
      if(cipher == NULL)
      {
        fprintf(stderr, "Error: unknown cipher: %s.\n\n", optarg);
        exit(EXIT_FAILURE);
      }
      break;

    case 'd':
      digest = EVP_get_digestbyname(optarg);
      if(digest == NULL)
      {
        fprintf(stderr, "Error: unknown digest: %s.\n\n", optarg);
        exit(EXIT_FAILURE);
      }
      break;

    case 'e':
      suffix_len = mbstowcs(NULL, optarg, 0);
      if(suffix_len == (unsigned int) -1)
      {
        fprintf(stderr, "Error: invalid character in suffix.\n\n");
        exit(EXIT_FAILURE);
      }
      suffix = (wchar_t *) calloc(suffix_len + 1, sizeof(wchar_t));
      if(suffix == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(suffix, optarg, suffix_len + 1);
      break;

    case 'f':
      dictionary = fopen(optarg, "r");
      if(dictionary == NULL)
      {
        fprintf(stderr, "Error: can't open dictionary file.\n\n");
        exit(EXIT_FAILURE);
      }
      break;

    case 'h':
      usage(argv[0]);
      exit(EXIT_FAILURE);
      break;

    case 'L':
      limit = (long unsigned int) atol(optarg);
      break;

    case 'l':
      min_len = (unsigned int) atoi(optarg);
      break;

    case 'M':
      magic = optarg;
      break;

    case 'm':
      max_len = (unsigned int) atoi(optarg);
      break;

    case 'N':
      no_error = 1;
      break;

    case 'n':
      no_salt = 1;
      break;

    case 's':
      charset_len = mbstowcs(NULL, optarg, 0);
      if(charset_len == 0)
      {
        fprintf(stderr, "Error: charset must have at least one character.\n\n");
        exit(EXIT_FAILURE);
      }
      if(charset_len == (unsigned int) -1)
      {
        fprintf(stderr, "Error: invalid character in charset.\n\n");
        exit(EXIT_FAILURE);
      }
      charset = (wchar_t *) calloc(charset_len + 1, sizeof(wchar_t));
      if(charset == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(charset, optarg, charset_len + 1);
      break;

    case 't':
      nb_threads = (unsigned int) atoi(optarg);
      if(nb_threads == 0)
        nb_threads = 1;
      break;

    case 'v':
      status_interval = (unsigned int) atoi(optarg);
      break;

    case 'w':
      state_file = optarg;
      break;

    default:
      usage(argv[0]);
      switch(optopt)
      {
      case 'B':
      case 'b':
      case 'c':
      case 'd':
      case 'e':
      case 'f':
      case 'L':
      case 'l':
      case 'M':
      case 'm':
      case 's':
      case 't':
      case 'v':
      case 'w':
        fprintf(stderr, "Error: missing argument for option: '-%c'.\n\n", optopt);
        break;

      default:
        fprintf(stderr, "Error: unknown option: '%c'.\n\n", optopt);
        break;
      }
      exit(EXIT_FAILURE);
      break;
    }

  if(optind >= argc)
  {
    usage(argv[0]);
    fprintf(stderr, "Error: missing filename.\n\n");
    exit(EXIT_FAILURE);
  }

  filename = argv[optind];

  /* Check variables */
  if(cipher == NULL)
    cipher = EVP_aes_256_cbc();
  if(digest == NULL)
    digest = EVP_md5();
  if(dictionary != NULL)
  {
    fprintf(stderr, "Warning: using dictionary mode, ignoring options -b, -e, -l, -m and -s.\n\n");
  }
  else
  {
    if(prefix == NULL)
    {
      prefix_len = mbstowcs(NULL, "", 0);
      prefix = (wchar_t *) calloc(prefix_len + 1, sizeof(wchar_t));
      if(prefix == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(prefix, "", prefix_len + 1);
    }
    if(suffix == NULL)
    {
      suffix_len = mbstowcs(NULL, "", 0);
      suffix = (wchar_t *) calloc(suffix_len + 1, sizeof(wchar_t));
      if(suffix == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(suffix, "", suffix_len + 1);
    }
    if(charset && binary)
    {
      fprintf(stderr, "Error: options -B and -s can't be both set.\n\n");
      exit(EXIT_FAILURE);
    }
    else if(binary)
    {
      charset_len = strlen(binary_charset);
      prefix_len = wcstombs(NULL, prefix, 0);
      suffix_len = wcstombs(NULL, suffix, 0);
    }
    else if(charset == NULL)
    {
      charset_len = mbstowcs(NULL, default_charset, 0);
      charset = (wchar_t *) calloc(charset_len + 1, sizeof(wchar_t));
      if(charset == NULL)
      {
        fprintf(stderr, "Error: memory allocation failed.\n\n");
        exit(EXIT_FAILURE);
      }
      mbstowcs(charset, default_charset, charset_len + 1);
    }
    if(charset_len == 0)
    {
      fprintf(stderr, "Error: charset must have at least one character.\n\n");
      exit(EXIT_FAILURE);
    }
    if(min_len < prefix_len + suffix_len + 1)
    {
      fprintf(stderr, "Warning: minimum length (%u) isn't bigger than the length of specified password characters (%u). Setting minimum length to %u.\n\n", min_len, prefix_len + suffix_len, prefix_len + suffix_len + 1);
      min_len = prefix_len + suffix_len + 1;
    }
    if(max_len < min_len)
    {
      fprintf(stderr, "Warning: maximum length (%u) is smaller than minimum length (%u). Setting maximum length to %u.\n\n", max_len, min_len, min_len);
      max_len = min_len;
    }
  }

  last_pass[0] = '\0';

  /* Check header */
  fd = open(filename, O_RDONLY);
  if(fd == -1)
  {
    perror("open file");
    exit(EXIT_FAILURE);
  }
  if(no_salt == 0)
  {
    memset(salt, 0, sizeof(salt));
    ret = read(fd, salt, 8);
    if(strncmp(salt, "Salted__", 8) != 0)
    {
      close(fd);
      fprintf(stderr, "Error: %s is not a salted openssl file.\n\n", filename);
      exit(EXIT_FAILURE);
    }

    /* Read salt */
    ret = read(fd, salt, 8);
    if(ret != 8)
    {
      close(fd);
      fprintf(stderr, "Error: could not read salt.\n\n");
      exit(EXIT_FAILURE);
    }
  }

  /* Read encrypted data */
  ret = fstat(fd, &file_stats);
  if(no_salt)
    data_len = file_stats.st_size;
  else
    data_len = file_stats.st_size - 16;
  data = (char *) malloc(data_len);
  if(data == NULL)
  {
    fprintf(stderr, "Error: memory allocation failed.\n\n");
    exit(EXIT_FAILURE);
  }
  for(i = 0; i < data_len;)
  {
    ret = read(fd, data + i, data_len - i);
    if(ret == -1)
    {
      close(fd);
      fprintf(stderr, "Error: could not read data.\n\n");
      exit(EXIT_FAILURE);
    }
    else if(ret > 0)
      i += ret;
  }
  close(fd);

  signal(SIGUSR1, handle_signal);
  if(status_interval > 0)
  {
    signal(SIGALRM, handle_signal);
    progress_timer.it_value.tv_sec = status_interval;
    progress_timer.it_value.tv_usec = 0;
    progress_timer.it_interval.tv_sec = status_interval;
    progress_timer.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &progress_timer, NULL);
  }

  pthread_mutex_init(&found_password_lock, NULL);
  pthread_mutex_init(&get_password_lock, NULL);
  
  decryption_threads = (pthread_t *) malloc(nb_threads * sizeof(pthread_t));
  thread_locals = (struct decryption_func_locals *) calloc(nb_threads, sizeof(struct decryption_func_locals));
  if((decryption_threads == NULL) || (thread_locals == NULL))
  {
    fprintf(stderr, "Error: memory allocation failed.\n\n");
    exit(EXIT_FAILURE);
  }

  start_time = time(NULL);

  if(state_file != NULL)
  {
    restore_state();

    signal(SIGVTALRM, save_state);
    state_timer.it_value.tv_sec = 60 * nb_threads;
    state_timer.it_value.tv_usec = 0;
    state_timer.it_interval.tv_sec = 60 * nb_threads;
    state_timer.it_interval.tv_usec = 0;
    setitimer(ITIMER_VIRTUAL, &state_timer, NULL);
  }

  /* Start decryption threads */
  for(i = 0; i < nb_threads; i++)
  {
    ret = pthread_create(&decryption_threads[i], NULL, &decryption_func, &thread_locals[i]);
    if(ret != 0)
    {
      perror("Error: decryption thread");
      exit(EXIT_FAILURE);
    }
  }

  for(i = 0; i < nb_threads; i++)
  {
    pthread_join(decryption_threads[i], NULL);
  }
  if(found_password == 0)
  {
    handle_signal(SIGUSR1); /* Print some stats */
    fprintf(stderr, "Password not found\n");
  }

  free(thread_locals);
  free(decryption_threads);
  pthread_mutex_destroy(&found_password_lock);
  pthread_mutex_destroy(&get_password_lock);
  free(data);
  EVP_cleanup();

  exit(EXIT_SUCCESS);
}
Ejemplo n.º 22
0
static void handle_received_frame(void) {
	uint8_t rx_length, length, *rx_ptr;

	// Take semaphore
	xSemaphoreTake(spi_mutex, portMAX_DELAY);

	// Check if there is at least one byte in fifo
	if (cc1101_status_rxbytes() == 0) {
		xSemaphoreGive(spi_mutex);
		restore_state();
		PRINTF("[PHY] no byte\n");
		return;
	}

	// Get length byte
	cc1101_fifo_get(&rx_length, 1);

	// Check length
	if (rx_length > PHY_MAX_LENGTH) {
		xSemaphoreGive(spi_mutex);
		restore_state();
		PRINTF("[PHY] length too big\n");
		return;
	}

	rx_data_length = rx_length;

	// Add 2 to the length for the status bytes
	rx_length += PHY_FOOTER_LENGTH;
	rx_ptr = rx_data;

	// Loop until end of packet
	while (cc1101_gdo0_read()) {
		// get the bytes in FIFO
		length = cc1101_status_rxbytes();

		// Check for overflow
		if (length & 0x80) {
			// Release semaphore
			xSemaphoreGive(spi_mutex);

			restore_state();
			PRINTF("[PHY] overflow\n");
			return;
		}

		// Check for local overflow
		if (length > rx_length) {
			// Release semaphore
			xSemaphoreGive(spi_mutex);
			restore_state();
			PRINTF("[PHY] local overflow\n");
			return;
		}

		// Read every byte but one, to prevent CC1101 bug.
		length -= 1;
		cc1101_fifo_get(rx_ptr, length);
		rx_ptr += length;
		rx_length -= length;

		// Wait until FIFO is filled above threshold, or EOP
		while (!cc1101_gdo2_read() && cc1101_gdo0_read()) {
			;
		}
	}

	// Packet complete, get the end
	length = cc1101_status_rxbytes();

	// Check for overflow
	if (length & 0x80) {
		// Release semaphore
		xSemaphoreGive(spi_mutex);
		restore_state();
		PRINTF("[PHY] overflow\n");
		return;
	}

	// Check for local overflow
	if (length > rx_length) {
		// Release semaphore
		xSemaphoreGive(spi_mutex);
		restore_state();
		PRINTF("[PHY] local overflow\n");
		return;
	}

	// Get the bytes
	cc1101_fifo_get(rx_ptr, length);
	rx_ptr += length;

	// Release semaphore
	xSemaphoreGive(spi_mutex);

	// Check CRC
	if ((rx_data[rx_data_length + 1] & 0x80) == 0) {
		// Bad CRC
		restore_state();
		PRINTF("[PHY] bad crc\n");
		return;
	}

	// Get RSSI
	int16_t rssi;
	rssi = rx_data[rx_data_length];
	if (rssi > 128) {
		rssi -= 256;
	}
	rssi -= 148;
	rssi /= 2;

	// Call callback function if any
	if (rx_cb) {
		rx_cb(rx_data, rx_data_length, (int8_t) rssi, sync_word_time);
	}

	// Restore state
	restore_state();
}
Ejemplo n.º 23
0
int cmd_merge(int argc, const char **argv, const char *prefix)
{
	unsigned char result_tree[20];
	struct strbuf buf = STRBUF_INIT;
	const char *head_arg;
	int flag, head_invalid = 0, i;
	int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0;
	struct commit_list *common = NULL;
	const char *best_strategy = NULL, *wt_strategy = NULL;
	struct commit_list **remotes = &remoteheads;

	if (file_exists(git_path("MERGE_HEAD")))
		die("You have not concluded your merge. (MERGE_HEAD exists)");
	if (read_cache_unmerged())
		die("You are in the middle of a conflicted merge."
				" (index unmerged)");

	/*
	 * Check if we are _not_ on a detached HEAD, i.e. if there is a
	 * current branch.
	 */
	branch = resolve_ref("HEAD", head, 0, &flag);
	if (branch && !prefixcmp(branch, "refs/heads/"))
		branch += 11;
	if (is_null_sha1(head))
		head_invalid = 1;

	git_config(git_merge_config, NULL);

	/* for color.ui */
	if (diff_use_color_default == -1)
		diff_use_color_default = git_use_color_default;

	argc = parse_options(argc, argv, prefix, builtin_merge_options,
			builtin_merge_usage, 0);
	if (verbosity < 0)
		show_diffstat = 0;

	if (squash) {
		if (!allow_fast_forward)
			die("You cannot combine --squash with --no-ff.");
		option_commit = 0;
	}

	if (!allow_fast_forward && fast_forward_only)
		die("You cannot combine --no-ff with --ff-only.");

	if (!argc)
		usage_with_options(builtin_merge_usage,
			builtin_merge_options);

	/*
	 * This could be traditional "merge <msg> HEAD <commit>..."  and
	 * the way we can tell it is to see if the second token is HEAD,
	 * but some people might have misused the interface and used a
	 * committish that is the same as HEAD there instead.
	 * Traditional format never would have "-m" so it is an
	 * additional safety measure to check for it.
	 */

	if (!have_message && is_old_style_invocation(argc, argv)) {
		strbuf_addstr(&merge_msg, argv[0]);
		head_arg = argv[1];
		argv += 2;
		argc -= 2;
	} else if (head_invalid) {
		struct object *remote_head;
		/*
		 * If the merged head is a valid one there is no reason
		 * to forbid "git merge" into a branch yet to be born.
		 * We do the same for "git pull".
		 */
		if (argc != 1)
			die("Can merge only exactly one commit into "
				"empty head");
		if (squash)
			die("Squash commit into empty head not supported yet");
		if (!allow_fast_forward)
			die("Non-fast-forward commit does not make sense into "
			    "an empty head");
		remote_head = peel_to_type(argv[0], 0, NULL, OBJ_COMMIT);
		if (!remote_head)
			die("%s - not something we can merge", argv[0]);
		update_ref("initial pull", "HEAD", remote_head->sha1, NULL, 0,
				DIE_ON_ERR);
		reset_hard(remote_head->sha1, 0);
		return 0;
	} else {
		struct strbuf msg = STRBUF_INIT;

		/* We are invoked directly as the first-class UI. */
		head_arg = "HEAD";

		/*
		 * All the rest are the commits being merged;
		 * prepare the standard merge summary message to
		 * be appended to the given message.  If remote
		 * is invalid we will die later in the common
		 * codepath so we discard the error in this
		 * loop.
		 */
		if (!have_message) {
			for (i = 0; i < argc; i++)
				merge_name(argv[i], &msg);
			fmt_merge_msg(option_log, &msg, &merge_msg);
			if (merge_msg.len)
				strbuf_setlen(&merge_msg, merge_msg.len-1);
		}
	}

	if (head_invalid || !argc)
		usage_with_options(builtin_merge_usage,
			builtin_merge_options);

	strbuf_addstr(&buf, "merge");
	for (i = 0; i < argc; i++)
		strbuf_addf(&buf, " %s", argv[i]);
	setenv("GIT_REFLOG_ACTION", buf.buf, 0);
	strbuf_reset(&buf);

	for (i = 0; i < argc; i++) {
		struct object *o;
		struct commit *commit;

		o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT);
		if (!o)
			die("%s - not something we can merge", argv[i]);
		commit = lookup_commit(o->sha1);
		commit->util = (void *)argv[i];
		remotes = &commit_list_insert(commit, remotes)->next;

		strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1));
		setenv(buf.buf, argv[i], 1);
		strbuf_reset(&buf);
	}

	if (!use_strategies) {
		if (!remoteheads->next)
			add_strategies(pull_twohead, DEFAULT_TWOHEAD);
		else
			add_strategies(pull_octopus, DEFAULT_OCTOPUS);
	}

	for (i = 0; i < use_strategies_nr; i++) {
		if (use_strategies[i]->attr & NO_FAST_FORWARD)
			allow_fast_forward = 0;
		if (use_strategies[i]->attr & NO_TRIVIAL)
			allow_trivial = 0;
	}

	if (!remoteheads->next)
		common = get_merge_bases(lookup_commit(head),
				remoteheads->item, 1);
	else {
		struct commit_list *list = remoteheads;
		commit_list_insert(lookup_commit(head), &list);
		common = get_octopus_merge_bases(list);
		free(list);
	}

	update_ref("updating ORIG_HEAD", "ORIG_HEAD", head, NULL, 0,
		DIE_ON_ERR);

	if (!common)
		; /* No common ancestors found. We need a real merge. */
	else if (!remoteheads->next && !common->next &&
			common->item == remoteheads->item) {
		/*
		 * If head can reach all the merge then we are up to date.
		 * but first the most common case of merging one remote.
		 */
		finish_up_to_date("Already up-to-date.");
		return 0;
	} else if (allow_fast_forward && !remoteheads->next &&
			!common->next &&
			!hashcmp(common->item->object.sha1, head)) {
		/* Again the most common case of merging one remote. */
		struct strbuf msg = STRBUF_INIT;
		struct object *o;
		char hex[41];

		strcpy(hex, find_unique_abbrev(head, DEFAULT_ABBREV));

		if (verbosity >= 0)
			printf("Updating %s..%s\n",
				hex,
				find_unique_abbrev(remoteheads->item->object.sha1,
				DEFAULT_ABBREV));
		strbuf_addstr(&msg, "Fast-forward");
		if (have_message)
			strbuf_addstr(&msg,
				" (no commit created; -m option ignored)");
		o = peel_to_type(sha1_to_hex(remoteheads->item->object.sha1),
			0, NULL, OBJ_COMMIT);
		if (!o)
			return 1;

		if (checkout_fast_forward(head, remoteheads->item->object.sha1))
			return 1;

		finish(o->sha1, msg.buf);
		drop_save();
		return 0;
	} else if (!remoteheads->next && common->next)
		;
		/*
		 * We are not doing octopus and not fast-forward.  Need
		 * a real merge.
		 */
	else if (!remoteheads->next && !common->next && option_commit) {
		/*
		 * We are not doing octopus, not fast-forward, and have
		 * only one common.
		 */
		refresh_cache(REFRESH_QUIET);
		if (allow_trivial && !fast_forward_only) {
			/* See if it is really trivial. */
			git_committer_info(IDENT_ERROR_ON_NO_NAME);
			printf("Trying really trivial in-index merge...\n");
			if (!read_tree_trivial(common->item->object.sha1,
					head, remoteheads->item->object.sha1))
				return merge_trivial();
			printf("Nope.\n");
		}
	} else {
		/*
		 * An octopus.  If we can reach all the remote we are up
		 * to date.
		 */
		int up_to_date = 1;
		struct commit_list *j;

		for (j = remoteheads; j; j = j->next) {
			struct commit_list *common_one;

			/*
			 * Here we *have* to calculate the individual
			 * merge_bases again, otherwise "git merge HEAD^
			 * HEAD^^" would be missed.
			 */
			common_one = get_merge_bases(lookup_commit(head),
				j->item, 1);
			if (hashcmp(common_one->item->object.sha1,
				j->item->object.sha1)) {
				up_to_date = 0;
				break;
			}
		}
		if (up_to_date) {
			finish_up_to_date("Already up-to-date. Yeeah!");
			return 0;
		}
	}

	if (fast_forward_only)
		die("Not possible to fast-forward, aborting.");

	/* We are going to make a new commit. */
	git_committer_info(IDENT_ERROR_ON_NO_NAME);

	/*
	 * At this point, we need a real merge.  No matter what strategy
	 * we use, it would operate on the index, possibly affecting the
	 * working tree, and when resolved cleanly, have the desired
	 * tree in the index -- this means that the index must be in
	 * sync with the head commit.  The strategies are responsible
	 * to ensure this.
	 */
	if (use_strategies_nr != 1) {
		/*
		 * Stash away the local changes so that we can try more
		 * than one.
		 */
		save_state();
	} else {
		memcpy(stash, null_sha1, 20);
	}

	for (i = 0; i < use_strategies_nr; i++) {
		int ret;
		if (i) {
			printf("Rewinding the tree to pristine...\n");
			restore_state();
		}
		if (use_strategies_nr != 1)
			printf("Trying merge strategy %s...\n",
				use_strategies[i]->name);
		/*
		 * Remember which strategy left the state in the working
		 * tree.
		 */
		wt_strategy = use_strategies[i]->name;

		ret = try_merge_strategy(use_strategies[i]->name,
			common, head_arg);
		if (!option_commit && !ret) {
			merge_was_ok = 1;
			/*
			 * This is necessary here just to avoid writing
			 * the tree, but later we will *not* exit with
			 * status code 1 because merge_was_ok is set.
			 */
			ret = 1;
		}

		if (ret) {
			/*
			 * The backend exits with 1 when conflicts are
			 * left to be resolved, with 2 when it does not
			 * handle the given merge at all.
			 */
			if (ret == 1) {
				int cnt = evaluate_result();

				if (best_cnt <= 0 || cnt <= best_cnt) {
					best_strategy = use_strategies[i]->name;
					best_cnt = cnt;
				}
			}
			if (merge_was_ok)
				break;
			else
				continue;
		}

		/* Automerge succeeded. */
		write_tree_trivial(result_tree);
		automerge_was_ok = 1;
		break;
	}

	/*
	 * If we have a resulting tree, that means the strategy module
	 * auto resolved the merge cleanly.
	 */
	if (automerge_was_ok)
		return finish_automerge(common, result_tree, wt_strategy);

	/*
	 * Pick the result from the best strategy and have the user fix
	 * it up.
	 */
	if (!best_strategy) {
		restore_state();
		if (use_strategies_nr > 1)
			fprintf(stderr,
				"No merge strategy handled the merge.\n");
		else
			fprintf(stderr, "Merge with strategy %s failed.\n",
				use_strategies[0]->name);
		return 2;
	} else if (best_strategy == wt_strategy)
		; /* We already have its result in the working tree. */
	else {
		printf("Rewinding the tree to pristine...\n");
		restore_state();
		printf("Using the %s to prepare resolving by hand.\n",
			best_strategy);
		try_merge_strategy(best_strategy, common, head_arg);
	}

	if (squash)
		finish(NULL, NULL);
	else {
		int fd;
		struct commit_list *j;

		for (j = remoteheads; j; j = j->next)
			strbuf_addf(&buf, "%s\n",
				sha1_to_hex(j->item->object.sha1));
		fd = open(git_path("MERGE_HEAD"), O_WRONLY | O_CREAT, 0666);
		if (fd < 0)
			die_errno("Could not open '%s' for writing",
				  git_path("MERGE_HEAD"));
		if (write_in_full(fd, buf.buf, buf.len) != buf.len)
			die_errno("Could not write to '%s'", git_path("MERGE_HEAD"));
		close(fd);
		strbuf_addch(&merge_msg, '\n');
		fd = open(git_path("MERGE_MSG"), O_WRONLY | O_CREAT, 0666);
		if (fd < 0)
			die_errno("Could not open '%s' for writing",
				  git_path("MERGE_MSG"));
		if (write_in_full(fd, merge_msg.buf, merge_msg.len) !=
			merge_msg.len)
			die_errno("Could not write to '%s'", git_path("MERGE_MSG"));
		close(fd);
		fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666);
		if (fd < 0)
			die_errno("Could not open '%s' for writing",
				  git_path("MERGE_MODE"));
		strbuf_reset(&buf);
		if (!allow_fast_forward)
			strbuf_addf(&buf, "no-ff");
		if (write_in_full(fd, buf.buf, buf.len) != buf.len)
			die_errno("Could not write to '%s'", git_path("MERGE_MODE"));
		close(fd);
	}

	if (merge_was_ok) {
		fprintf(stderr, "Automatic merge went well; "
			"stopped before committing as requested\n");
		return 0;
	} else
		return suggest_conflicts();
}
Ejemplo n.º 24
0
        debug_win::debug_win(
                m::post_office_ptr p,
                us::user_service_ptr us, 
                s::conversation_service_ptr ss, 
                const n::udp_stats& udps,
                QWidget* parent) :
            QDialog{parent},
            _post{p},
            _user_service{us},
            _conversation_service{ss},
            _udp_stats(udps)
        {
            REQUIRE(p);
            REQUIRE(us);
            REQUIRE(ss);

            //main layout
            auto* layout = new QVBoxLayout{this};
            setLayout(layout);
            auto* tabs = new QTabWidget{this};
            tabs->setTabPosition(QTabWidget::West);
            layout->addWidget(tabs);

            //create log tab
            auto* log_tab = new QWidget;
            auto* log_layout = new QGridLayout{log_tab};

            _log = new QTextEdit;
            log_layout->addWidget(_log, 0,0);

            //udp stats
            _udp_stat_text = new QLabel; 

            //create mailbox tab
            auto* mailbox_tab = new QWidget;
            auto* mailbox_layout = new QGridLayout{mailbox_tab};
            _mailboxes = new list;
            mailbox_layout->addWidget(_udp_stat_text, 0,0);
            mailbox_layout->addWidget(_mailboxes, 1,0);


            //add tabs
            tabs->addTab(log_tab, tr("log"));
            tabs->addTab(mailbox_tab, tr("mailboxes"));

            //add outside message queue to mailboxes tab
            auto outside = new queue_debug{convert(tr("outside")), _post->outside_stats()};
            _mailboxes->add(outside);

            //fill tabs with data 
            update_mailboxes();
            update_log();

            //setup timers
            auto *t = new QTimer(this);
            connect(t, SIGNAL(timeout()), this, SLOT(update_log()));
            t->start(UPDATE_LOG);

            auto *t2 = new QTimer(this);
            connect(t2, SIGNAL(timeout()), this, SLOT(update_mailboxes()));
            t2->start(UPDATE_MAILBOXES);

            auto *t3 = new QTimer(this);
            connect(t3, SIGNAL(timeout()), this, SLOT(update_udp_stats()));
            t3->start(UPDATE_GRAPH);

            restore_state();

            ENSURE(_log);
            ENSURE(_post);
            ENSURE(_user_service);
            ENSURE(_conversation_service);
        }
Ejemplo n.º 25
0
 virtual void destroy() { restore_state(); }
Ejemplo n.º 26
0
/*!
 * @brief Injects meterpreter stage library in a process.
 * @param pid Process identifier to inject.
 * @param l Pointer to the \c library to inject.
 * @returns Indication of success or failure.
 * @retval 0 indicates success.
 */
LONG
inject_library(LONG pid, library *l) {
	state s;
	long code_mem;
	long stack_mem;
	struct user_regs_struct regs;
	ULONG library_size = _SIZE_OF(l->length);
	unsigned long *buf_ptr = (unsigned long *)l->data;
	LONG result = 0;

	if (l == NULL) {
		result = ERROR_INVALID_PARAMETER;
		goto end;
	}

	dprintf("[INJECT] Saving state");
	result = attach(pid);
	if (result != 0)
		goto end;

	result = save_state(pid, &s);
	if (result != 0)
		goto end;

	memcpy(&regs, &(s.regs), sizeof(struct user_regs_struct));

	dprintf("[INJECT] Creating new code memory");
	result = allocate(pid, &regs, 0, CODE_SIZE);
	dprintf("[DEBUG] result: %d", result);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] New code memory on 0x%x, fixing registers", regs.eax);
	code_mem = regs.eax;
	regs.eip = code_mem;

	result = setregs(pid, &regs);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] Restoring code on original process");
	restore_state(pid, &s, 1);

	dprintf("[INJECT] Creating new stack");
  	result = allocate(pid, &regs, 0, STACK_SIZE);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] New stack on 0x%x, fixing registers", regs.eax);
	stack_mem = regs.eax + STACK_SIZE;
	regs.esp = stack_mem;
	regs.eip = code_mem;

	result = setregs(pid, &regs);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] Allocating space for the library...");
	result = allocate(pid, &regs, l->base_addr, l->length);
	if (result != 0)
		goto restore;

	if (regs.eax != l->base_addr) {
		result = EFAULT;
		goto restore;
	}

	dprintf("[INJECT] Copying payload to 0x%x", regs.eax);
	result = write_memory(pid, regs.eax, buf_ptr, library_size);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] Fixing registers");
	regs.esp = stack_mem;
	regs.eip = code_mem;
	result = setregs(pid, &regs);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] Executing call stub");
	result = call(pid, &regs, l->entry_point);
	if (result != 0)
		goto restore;

	dprintf("[INJECT] The payload has warned successfully, migration has been successfully");
	result = detach(pid);
	goto end;

restore:
	restore_state(pid, &s, 0);
end:
	return result;
}
static MateComponent_Canvas_ArtUTA *
impl_MateComponent_Canvas_Component_update (PortableServer_Servant     servant,
				     const MateComponent_Canvas_State *state,
				     const MateComponent_Canvas_affine aff,
				     const MateComponent_Canvas_SVP   *clip_path,
				     CORBA_long                 flags,
				     CORBA_double              *x1, 
				     CORBA_double              *y1, 
				     CORBA_double              *x2, 
				     CORBA_double              *y2, 
				     CORBA_Environment         *ev)
{
	Gcc *gcc = GCC (matecomponent_object_from_servant (servant));
	MateCanvasItem *item = MATE_CANVAS_ITEM (gcc->priv->item);
	double affine [6];
	int i;
	ArtSVP *svp = NULL;
	MateComponent_Canvas_ArtUTA *cuta;

	MateCanvasItemClass *gci_class = g_type_class_ref (
					mate_canvas_item_get_type ());

	restore_state (item, state);
	for (i = 0; i < 6; i++)
		affine [i] = aff [i];

	if (clip_path->_length > 0) {
		svp = art_alloc (sizeof (ArtSVP) + (clip_path->_length * sizeof (ArtSVPSeg)));
		if (svp == NULL)
			goto fail;

		svp->n_segs = clip_path->_length;
		
		for (i = 0; svp->n_segs; i++) {
			gboolean ok;
		
			ok = CORBA_SVP_Segment_to_SVPSeg (&clip_path->_buffer [i], &svp->segs [i]);

			if (!ok) {
				int j;

				for (j = 0; j < i; j++) {
					free_seg (&svp->segs [j]);
					art_free (svp);
					goto fail;
				}
			}
		}
	}

	invoke_update (item, (double *)aff, svp, flags);

	if (svp){
		for (i = 0; i < svp->n_segs; i++)
			free_seg (&svp->segs [i]);
		art_free (svp);
	}

 fail:
	if (getenv ("CC_DEBUG"))
		printf ("%g %g %g %g\n", item->x1, item->x2, item->y1, item->y2);
	*x1 = item->x1;
	*x2 = item->x2;
	*y1 = item->y1;
	*y2 = item->y2;

	cuta = CORBA_UTA (item->canvas->redraw_area);
	if (cuta == NULL) {
		CORBA_exception_set_system (ev, ex_CORBA_NO_MEMORY, CORBA_COMPLETED_NO);
		return NULL;
	}

	/*
	 * Now, mark our canvas as fully up to date
	 */

        /* Clears flags for root item. */
	(* gci_class->update) (item->canvas->root, affine, svp, flags);

	if (item->canvas->redraw_area) {
		art_uta_free (item->canvas->redraw_area);
		item->canvas->redraw_area = NULL;
	}
	item->canvas->need_redraw = FALSE;
	
	return cuta;
}