/**
 * \brief detect and resolve IP conflict
 * \param the ethernet interface entry in the MIB for which we change the IP
 * \param interface the name of this interface (eth0/enp2s0/lo...)
 * \return TRUE if conflict could be resolved, FALSE otherwise
 */
gboolean ip_conflict_detection(  struct ethernetIfTableEntry *if_entry, gchar *interface ){

	g_debug ("ip_conflict_detection()" );

	/* select a random time to wait between 0 en PROBE_WAIT */
	srand(time(NULL));
	/* PROBE_WAIT is given in second, if we want a integer value for microsecond , we should multiply it by 1000000 */
	gdouble probe_wait =  ((gdouble) rand()/ (gdouble)(RAND_MAX)) * PROBE_WAIT;
	/* send PROB_NUM ARP PROBE messages between space randomly between PROBE_MIN and PROBE_MAX number*/
	gdouble space = (((gdouble) rand()/ (gdouble)(RAND_MAX)) /  (gdouble) ((PROBE_MAX - PROBE_MIN) * PROBE_NUM));
	gdouble time_passed = 0 ;
	gboolean conflict = TRUE ;
	in_addr_t max_ip_value = inet_addr ( DEFAULT_STATIC_IP ) ;

	GTimer *timer = g_timer_new();

	/* wait probe_wait */
	g_debug ("waiting %G second(s)", probe_wait);
	g_timer_start( timer );
	while(time_passed < probe_wait){
		time_passed = g_timer_elapsed ( timer, NULL );
	}

	int sending_socket_fd;
	struct sockaddr_ll sa;
	if ( !prepare_arp_request_socket (if_entry , &sending_socket_fd , &sa )){
		g_critical("cannot prepare socket for ARP request");
		return FALSE;
	}

	/* variable for the ethernet frame to build */
	struct arp_packet pkt;
	int ethernet_frame_length;
	uint8_t *ethernet_frame;

	while ( conflict ){

		/* build the ethernet frame */
		ethernet_frame = init_ethernet_frame (if_entry , &pkt, &ethernet_frame_length, TRUE );
		if ( !ethernet_frame  ){
			g_critical("cannot build ethernet frame for ARP request");
			return FALSE;
		}

		/* wait PROBE_MIN */
		g_debug ("waiting %d second(s)", PROBE_MIN);
		g_timer_reset( timer );
		time_passed = g_timer_elapsed ( timer, NULL );
		while( time_passed  <  (PROBE_MIN) ){
			time_passed = g_timer_elapsed ( timer, NULL );
		}

		/* send ARP PROBE message PROBE_NUM times with an interval probe_wait */
		g_debug("send ARP Probe message %d times every %G second(s)", PROBE_NUM, space);
		for( int i = 1 ; i <= PROBE_NUM ; i ++){

			g_timer_reset( timer );
			time_passed = g_timer_elapsed ( timer, NULL );
			while( time_passed  <  space ){
				time_passed = g_timer_elapsed ( timer, NULL );
			}

			send_arp_request( sending_socket_fd , ethernet_frame, ethernet_frame_length, sa );

		}

		conflict = receive_arp_reply( ) ;

		/* if receive_arp_reply return FALSE there is a conflict, else, we are fine with this IP  */
		if ( conflict ){
			struct in_addr device_ip;
			device_ip.s_addr = if_entry->ethernetIfIpAddress ;
			g_debug("IP address %s already in use", inet_ntoa ( device_ip ));
			/* pick up a new random IP */
			if_entry->ethernetIfIpAddressConflict 	= if_entry->ethernetIfIpAddress ;
			if_entry->ethernetIfIpAddress 			= random_ip_for_conflict(interface);
			if ( if_entry->ethernetIfIpAddress == max_ip_value )
			   return TRUE;
			/* send trap */
			send_ipAddressConflict_trap();
		}
	}

	/* build and send probe message */
	ethernet_frame = init_ethernet_frame (if_entry , &pkt, &ethernet_frame_length, FALSE );
	send_arp_request( sending_socket_fd , ethernet_frame, ethernet_frame_length, sa );

	/* close sockets */
	close ( sending_socket_fd );

	/* free the ethernet frame build */
	free(ethernet_frame);

	return FALSE;

}
示例#2
0
exchange *
exchange_new ( const guint uid,
               const gchar *name,
               const gchar *desc,
               const gchar *path )
{
  exchange *e;
  gchar *filename, *path_asks, *path_bids;
  gboolean error;

#ifdef PROFILE_EXCHANGE_NEW
  GTimer *timer;
  gdouble duration_store;
  gdouble duration_clear;
  timer = g_timer_new ( );
#endif

  e = (exchange *) g_malloc ( sizeof(exchange) );

  e->uid = uid;
  e->name = g_strdup ( name );
  e->desc = g_strdup ( desc );
  e->path = g_strdup ( path );

#ifdef PROFILE_EXCHANGE_NEW
  g_timer_start ( timer );
#endif

  filename = g_build_filename ( path, name, "data.csv", NULL );

  e->store = refstore_new ( filename, (refstore_cb_append *) _append_data_to_views, e );

  e->views[VIEW_LENGTH_10_MN] = refview_new ( e->store, 't', "10min", 600, "10s", 10 );
  e->views[VIEW_LENGTH_1_H] = refview_new ( e->store, 'h', "1h", 3600, "30s", 30 );
  e->views[VIEW_LENGTH_2_H] = refview_new ( e->store, 'a', "2h", 3600*2, "1m", 60 );
  e->views[VIEW_LENGTH_4_H] = refview_new ( e->store, 'o', "4h", 3600*4, "2m", 120 );
  e->views[VIEW_LENGTH_8_H] = refview_new ( e->store, 's', "8h", 3600*8, "3m", 180 );
  e->views[VIEW_LENGTH_12_H] = refview_new ( e->store, 'n', "12h", 3600*12, "5m", 300 );
  e->views[VIEW_LENGTH_1_D] = refview_new ( e->store, 'd', "1d", 3600*24, "10m", 600 );
  e->views[VIEW_LENGTH_3_D] = refview_new ( e->store, 'r', "3d", 3600*24*3, "30m", 600*3 );
  e->views[VIEW_LENGTH_1_W] = refview_new ( e->store, 'w', "1w", 3600*24*7, "1h", 3600 );
  e->views[VIEW_LENGTH_2_W] = refview_new ( e->store, 'q', "2w", 3600*24*14, "2h", 3600*2 );
  e->views[VIEW_LENGTH_1_M] = refview_new ( e->store, 'm', "1m", 3600*24*31, "6h", 3600*6 );
  e->views[VIEW_LENGTH_3_M] = refview_new ( e->store, 'e', "3m", 3600*24*92, "12h", 3600*12 );
  e->views[VIEW_LENGTH_6_M] = refview_new ( e->store, 'b', "6m", 3600*24*183, "1d", 3600*24 );
  e->views[VIEW_LENGTH_1_Y] = refview_new ( e->store, 'y', "1y", 3600*24*365, "2d", 3600*24*2 );
  e->views[VIEW_LENGTH_2_Y] = refview_new ( e->store, 'z', "2y", 3600*24*365*2, "4d", 3600*24*4 );

#ifdef _WITH_STORE_GZIP_PACKS
  error = refstore_read_from_filez ( e->store );
#else
  error = refstore_read_from_file ( e->store );
#endif

  if ( error )
    log_print ( "core: store %s: unable to load store \'%s\'\n", e->name, filename );

  _finalize_views ( e );

#ifdef PROFILE_EXCHANGE_NEW
  g_timer_stop ( timer );
  duration_store = g_timer_elapsed ( timer, NULL );
  g_timer_start ( timer );
#endif

  refstore_clear ( e->store, FALSE ); /* in case it is fully in-memory, storage can bee freed after views init */

#ifdef PROFILE_EXCHANGE_NEW
  g_timer_stop ( timer );
  duration_clear = g_timer_elapsed ( timer, NULL );
  log_print ( "profile: %s: store=%.1fms  clear=%.1fms\n", name, duration_store*1000, duration_clear*1000 );
  g_timer_destroy ( timer );
#endif

#ifdef _WITH_BOOK_STAMP
  path_asks = g_build_filename ( path, name, "asks", NULL );
  path_bids = g_build_filename ( path, name, "bids", NULL );
#else
  path_asks = g_build_filename ( path, name, "asks.csv", NULL );
  path_bids = g_build_filename ( path, name, "bids.csv", NULL );
#endif

  e->book = refbook_new ( path_asks, path_bids );

#ifdef _WITH_BOOK_STAMP
  error = refbook_read_from_files ( e->book, NULL );
#else
  error = refbook_read_from_files ( e->book );
#endif

  e->cache_ticker = jcache_new ( 2*7 );
  e->cache_ticker->start += sprintf ( e->cache_ticker->content, "\"%s\":{", e->name );

  if ( error )
    log_print ( "core: book %s: unable to load initial book\n", e->name );

  g_free ( filename );
  g_free ( path_asks );
  g_free ( path_bids );
  return e;
}
static gboolean
trash_empty_update_dialog (gpointer user_data)
{
        gsize deleted, total;
        GFile *file;
        gboolean actually_deleting;

        g_assert (trash_empty_update_pending);

        deleted = trash_empty_deleted_files;
        total = trash_empty_total_files;
        file = trash_empty_current_file;
        actually_deleting = trash_empty_actually_deleting;

        /* maybe the done() got processed first. */
        if (!trash_empty_dialog)
                goto out;

        if (!actually_deleting) {
                /* If we havent finished counting yet, then pulse the progressbar every 100ms.
                 * This stops the user from thinking the dialog has frozen if there are
                 * a lot of files to delete. We don't pulse it every time we are called from the
                 * worker thread, otherwise it moves to fast and looks hideous
                 */
                if (timer) {
                        if (g_timer_elapsed (timer, NULL) > 0.1) {
                                gtk_progress_bar_pulse (GTK_PROGRESS_BAR (progressbar));
                                g_timer_start (timer);
                        }
                } else {
                        timer = g_timer_new ();
                        g_timer_start (timer);
                        gtk_progress_bar_pulse (GTK_PROGRESS_BAR (progressbar));
                }
        } else {
                gchar *text;
                gchar *tmp;
                gchar *markup;
                GFile *parent;

                text = g_strdup_printf (_("Removing item %lu of %lu"),
                                        deleted, total);
                gtk_progress_bar_set_text (GTK_PROGRESS_BAR (progressbar), text);

                g_free (text);

                if (deleted > total)
                        gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progressbar), 1.0);
                else
                        gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progressbar),
                                                       (gdouble) deleted / (gdouble) total);

                parent = g_file_get_parent (file);
                text = g_file_get_uri (parent);
                g_object_unref (parent);

                gtk_label_set_text (GTK_LABEL (location_label), text);
                g_free (text);

                tmp = g_file_get_basename (file);
                text = g_markup_printf_escaped (_("Removing: %s"), tmp);
                markup = g_strdup_printf ("<i>%s</i>", text);
                gtk_label_set_markup (GTK_LABEL (file_label), text);
                g_free (markup);
                g_free (text);
                g_free (tmp);

                /* unhide the labels */
                gtk_widget_show_all (GTK_WIDGET (trash_empty_dialog));
        }

out:
        trash_empty_current_file = NULL;
        g_object_unref (file);

        trash_empty_update_pending = FALSE;

        return FALSE;
}
示例#4
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	struct sigaction sa;
	struct wispr_session wispr;
	int index = 0;

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		return 1;
	}

	g_option_context_free(context);

	memset(&wispr, 0, sizeof(wispr));
	wispr_msg_init(&wispr.msg);

	wispr.web = g_web_new(index);
	if (wispr.web == NULL) {
		fprintf(stderr, "Failed to create web service\n");
		return 1;
	}

	if (option_debug == TRUE)
		g_web_set_debug(wispr.web, web_debug, "WEB");

	main_loop = g_main_loop_new(NULL, FALSE);

	if (option_nameserver != NULL) {
		g_web_add_nameserver(wispr.web, option_nameserver);
		g_free(option_nameserver);
	}

	g_web_set_accept(wispr.web, NULL);
	g_web_set_user_agent(wispr.web, "SmartClient/%s wispr", VERSION);
	g_web_set_close_connection(wispr.web, TRUE);

	if (option_url == NULL)
		option_url = g_strdup(DEFAULT_URL);

	wispr.username = option_username;
	wispr.password = option_password;
	wispr.originurl = option_url;

	timer = g_timer_new();

	wispr.parser = g_web_parser_new("<WISPAccessGatewayParam",
						"WISPAccessGatewayParam>",
						parser_callback, &wispr);

	wispr.request = g_web_request_get(wispr.web, option_url,
							wispr_result, &wispr);

	if (wispr.request == 0) {
		fprintf(stderr, "Failed to start request\n");
		return 1;
	}

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sig_term;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	g_main_loop_run(main_loop);

	g_timer_destroy(timer);

	if (wispr.request > 0)
		g_web_cancel_request(wispr.web, wispr.request);

	g_web_parser_unref(wispr.parser);
	g_web_unref(wispr.web);

	g_main_loop_unref(main_loop);

	g_free(wispr.username);
	g_free(wispr.password);
	g_free(wispr.originurl);

	return 0;
}
示例#5
0
static gboolean
lr_fastestmirror_perform(GSList *list,
                         LrFastestMirrorCb cb,
                         void *cbdata,
                         GError **err)
{
    assert(!err || *err == NULL);

    if (!list)
        return TRUE;

    CURLM *multihandle = curl_multi_init();
    if (!multihandle) {
        g_set_error(err, LR_FASTESTMIRROR_ERROR, LRE_CURL,
                    "curl_multi_init() error");
        return FALSE;
    }

    // Add curl easy handles to multi handle
    long handles_added = 0;
    for (GSList *elem = list; elem; elem = g_slist_next(elem)) {
        LrFastestMirror *mirror = elem->data;
        if (mirror->curl) {
            curl_multi_add_handle(multihandle, mirror->curl);
            handles_added++;
        }
    }

    if (handles_added == 0) {
        curl_multi_cleanup(multihandle);
        return TRUE;
    }

    cb(cbdata, LR_FMSTAGE_DETECTION, (void *) &handles_added);

    int still_running;
    gdouble elapsed_time = 0.0;
    GTimer *timer = g_timer_new();
    g_timer_start(timer);

    do {
        struct timeval timeout;
        int rc, cm_rc;
        int maxfd = -1;
        long curl_timeout = -1;
        fd_set fdread, fdwrite, fdexcep;

        FD_ZERO(&fdread);
        FD_ZERO(&fdwrite);
        FD_ZERO(&fdexcep);

        // Set suitable timeout to play around with
        timeout.tv_sec  = 0;
        timeout.tv_usec = HALF_OF_SECOND_IN_MICROS;

        cm_rc = curl_multi_timeout(multihandle, &curl_timeout);
        if (cm_rc != CURLM_OK) {
            g_set_error(err, LR_FASTESTMIRROR_ERROR, LRE_CURLM,
                        "curl_multi_timeout() error: %s",
                        curl_multi_strerror(cm_rc));
            curl_multi_cleanup(multihandle);
            return FALSE;
        }

        // Set timeout to a reasonable value
        if (curl_timeout >= 0) {
            timeout.tv_sec = curl_timeout / 1000;
            if (timeout.tv_sec >= 1) {
                timeout.tv_sec = 0;
                timeout.tv_usec = HALF_OF_SECOND_IN_MICROS;
            } else {
                timeout.tv_usec = (curl_timeout % 1000) * 1000;
                if (timeout.tv_usec > HALF_OF_SECOND_IN_MICROS)
                    timeout.tv_usec = HALF_OF_SECOND_IN_MICROS;
            }
        }

        // Get file descriptors from the transfers
        cm_rc = curl_multi_fdset(multihandle, &fdread, &fdwrite,
                                 &fdexcep, &maxfd);
        if (cm_rc != CURLM_OK) {
            g_set_error(err, LR_FASTESTMIRROR_ERROR, LRE_CURLM,
                        "curl_multi_fdset() error: %s",
                        curl_multi_strerror(cm_rc));
            return FALSE;
        }

        rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
        if (rc < 0) {
            if (errno == EINTR) {
                g_debug("%s: select() interrupted by signal", __func__);
            } else {
                g_set_error(err, LR_FASTESTMIRROR_ERROR, LRE_SELECT,
                            "select() error: %s", strerror(errno));
                return FALSE;
            }
        }

        curl_multi_perform(multihandle, &still_running);

        // Break loop after some reasonable amount of time
        elapsed_time = g_timer_elapsed(timer, NULL);

    } while(still_running && elapsed_time < LENGT_OF_MEASUREMENT);

    g_timer_destroy(timer);

    // Remove curl easy handles from multi handle
    // and calculate plain_connect_time
    for (GSList *elem = list; elem; elem = g_slist_next(elem)) {
        LrFastestMirror *mirror = elem->data;
        CURL *curl = mirror->curl;

        if (!curl)
            continue;

        // Remove handle
        curl_multi_remove_handle(multihandle, curl);

        // Calculate plain_connect_time
        char *effective_url;
        curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url);

        if (!effective_url) {
            // No effective url is most likely an error
            mirror->plain_connect_time = DBL_MAX;
        } else if (g_str_has_prefix(effective_url, "file://")) {
            // Local directories are considered to be the best mirrors
            mirror->plain_connect_time = 0.0;
        } else {
            // Get connect time
            double namelookup_time;
            double connect_time;
            double plain_connect_time;
            curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &namelookup_time);
            curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &connect_time);

            if (connect_time == 0.0) {
                // Zero connect time is most likely an error
                plain_connect_time = DBL_MAX;
            } else {
                plain_connect_time = connect_time - namelookup_time;
            }

            mirror->plain_connect_time = plain_connect_time;
            //g_debug("%s: name_lookup: %3.6f connect_time:  %3.6f (%3.6f) | %s",
            //        __func__, namelookup_time, connect_time,
            //        mirror->plain_connect_time, mirror->url);
        }
    }

    curl_multi_cleanup(multihandle);
    return TRUE;
}
示例#6
0
文件: emulate.c 项目: CZ-NIC/dionaea
void emulate_thread(gpointer data, gpointer user_data)
{
	struct emu_emulate_ctx *ctx = user_data;
	struct emu_config *conf = ctx->config;
	struct emu *e = ctx->emu;
	struct emu_env *env = ctx->env;
	int ret;

	g_mutex_lock(&ctx->mutex);

	if( ctx->state == waiting )
		ctx->state = running;


	if( ctx->time == NULL )
		ctx->time = g_timer_new();
	else
		g_timer_continue(ctx->time);

	while( ctx->state == running )
	{
		if( (ctx->steps % (1024*1024)) == 0 )
		{
			g_debug("steps %li", ctx->steps);
			if( ctx->steps > conf->limits.steps )
			{
				g_info("shellcode took too many steps ... (%li steps)",  ctx->steps);
				ctx->state = failed;
				break;
			}
			if( conf->limits.cpu > 0. )
			{
				double elapsed = g_timer_elapsed(ctx->time, NULL);
				if( elapsed > conf->limits.cpu )
				{
					g_info("shellcode took too long ... (%f seconds)",  elapsed);
					ctx->state = failed;
					break;
				}
			}
		}
		ctx->steps++;
		struct emu_env_hook *hook = NULL;
		hook = emu_env_w32_eip_check(env);

		if( hook != NULL )
		{
			if( hook->hook.win->fnhook == NULL )
			{
				g_critical("unhooked call to %s", hook->hook.win->fnname);
				break;
			} else
				if( ctx->state == waiting )
				/* for now, we stop!
				 * had a blocking io call
				 * callback from main will come at a given point
				 * and requeue us to the threadpool
				 */
				goto unlock_and_return;
		} else
		{
			ret = emu_cpu_parse(emu_cpu_get(e));
			struct emu_env_hook *hook =NULL;
			if( ret != -1 )
			{
				hook = emu_env_linux_syscall_check(env);
				if( hook == NULL )
				{
					ret = emu_cpu_step(emu_cpu_get(e));
				} else
				{
					if( hook->hook.lin->fnhook != NULL )
					{
						hook->hook.lin->fnhook(env, hook);
						if( ctx->state == waiting )
							/* stop 
							 * as mentioned previously
							 */
							goto unlock_and_return;
					}
				}
			}

			if( ret == -1 )
			{
				g_debug("cpu error %s", emu_strerror(e));
				break;
			}
		}
	}

	g_timer_stop(ctx->time);

	if( ctx->state == failed )
		g_debug("emulating shellcode failed");

	g_mutex_unlock(&ctx->mutex);

#ifdef DEBUG
	double elapsed = g_timer_elapsed(ctx->time, NULL);
	g_debug("shellcode took %f seconds on cpu, %li steps", elapsed, ctx->steps);
#endif

	GAsyncQueue *aq = g_async_queue_ref(g_dionaea->threads->cmds);
	g_async_queue_push(aq, async_cmd_new(emulate_ctx_free, ctx));
	g_async_queue_unref(aq);
	ev_async_send(g_dionaea->loop, &g_dionaea->threads->trigger);
	return;


	unlock_and_return:
	g_timer_stop(ctx->time);
	g_mutex_unlock(&ctx->mutex);
}
示例#7
0
int main(int argc, char **argv)
{
  struct NaClApp state, *nap = &state;
  struct SystemManifest sys_mft;
  struct GioMemoryFileSnapshot main_file;
  GTimer *timer;

  /* zerovm initialization */
  memset(nap, 0, sizeof *nap);
  nap->system_manifest = &sys_mft;
  memset(nap->system_manifest, 0, sizeof *nap->system_manifest);
  gnap = nap;

  ParseCommandLine(nap, argc, argv);
  NaClSignalHandlerInit();
  NaClSyscallTableInit();

  /* initialize mem_map and set nap fields to default values */
  ZLOGFAIL(NaClAppCtor(nap) == 0, EFAULT, "Error while constructing app state");

  /* We use the signal handler to verify a signal took place. */
  if(nap->skip_qualification == 0) NaClRunSelQualificationTests();

  /* Remove the signal handler if we are not using it. */
  if(nap->handle_signals == 0)
  {
    NaClSignalHandlerFini();
    NaClSignalAssertNoHandlers(); /* Sanity check. */
  }

  /* read nexe into memory */
  timer = g_timer_new();
  ZLOGFAIL(0 == GioMemoryFileSnapshotCtor(&main_file, nap->system_manifest->nexe),
      ENOENT, "Cannot open '%s'. %s", nap->system_manifest->nexe, strerror(errno));

#define TIMER_REPORT(msg) \
  do {\
    ZLOGS(LOG_DEBUG, msg " took %.3f milliseconds",\
        g_timer_elapsed(timer, NULL) * NACL_MICROS_PER_MILLI);\
    g_timer_start(timer);\
  } while(0)

  TIMER_REPORT("GioMemoryFileSnapshotCtor()");

  /* validate given nexe (ensure that text segment is safe) */
  ValidateNexe(nap);
  TIMER_REPORT("ValidateNexe()");

  /* validate nexe structure (check elf header and segments) */
  ZLOGS(LOG_DEBUG, "Loading nacl file %s", nap->system_manifest->nexe);
  NaClAppLoadFile((struct Gio *) &main_file, nap);
  TIMER_REPORT("NaClAppLoadFile()");

  if(-1 == (*((struct Gio *)&main_file)->vtbl->Close)((struct Gio *)&main_file))
    ZLOG(LOG_ERROR, "Error while closing '%s'", nap->system_manifest->nexe);
  (*((struct Gio *) &main_file)->vtbl->Dtor)((struct Gio *) &main_file);

  /* quit if fuzz testing specified */
  if(nap->quit_after_load)
  {
    SetExitState(OK_STATE);
    NaClExit(0);
  }

  /* setup zerovm from manifest */
  SystemManifestCtor(nap);

  /* "defence in depth" call */
  LastDefenseLine(nap);

  /* start accounting */
  AccountingCtor(nap);

  /* Make sure all the file buffers are flushed before entering the nexe */
  fflush((FILE*) NULL);
  TIMER_REPORT("nexe start preparation");

  /* set user code trap() exit location and switch to the user code */
  if(setjmp(user_exit) == 0)
    ZLOGFAIL(!NaClCreateMainThread(nap), EFAULT, "switching to nexe failed");
  SetExitState(OK_STATE);
  TIMER_REPORT("NaClCreateMainThread()");

  /* zerovm exit with finalization, report and stuff */
  NaClExit(0);

  /* Unreachable, but having the return prevents a compiler error. */
  return -1;
}
示例#8
0
文件: autoptr.c 项目: Babelz/SaNi
static void
test_g_timer (void)
{
  g_autoptr(GTimer) val = g_timer_new ();
  g_assert (val != NULL);
}
示例#9
0
static void ExecuteStatement(GNode* node, gpointer data)
{
	Statement* stmt = (Statement*) node->data;
	Verbose("* Visiting GNode at level %d", g_node_depth(node));

	if (parseOnly && (stmt->type < STMT_REPEAT)) return;

	switch (stmt->type) {
		case STMT_ASSIGN: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* varident = param_string_get(paramList, 0, &status[0]);
			Expression* expression = param_index_get(paramList, 1);

			// evaluator error check
			if (status[0] != STATUS_EVAL_OK) {
				Error("Malicious assign parameters! (status = %s)", expr_status_to_string(status[0]));
			}

			switch (expression->type) {
				case EXPR_RICH_INT:
				case EXPR_CONSTANT_INT: {
					Verbose("~ Executing STMT_ASSIGN: variable = %s, type = INT", varident);
					glong result = param_int_get(paramList, 1, &status[1]);

					// evaluator error check
					if (status[1] != STATUS_EVAL_OK) {
						Error("Malicious assign parameters! (status = %s)", expr_status_to_string(status[1]));
					}

					var_set_value(varident, VAR_INT, &result);
					break;
				}

				case EXPR_RICH_STRING:
				case EXPR_CONSTANT_STRING: {
					Verbose("~ Executing STMT_ASSIGN: variable = %s, type = STRING", varident);
					gchar* result_raw = param_string_get(paramList, 1, &status[1]);

					// evaluator error check
					if (status[1] != STATUS_EVAL_OK) {
						Error("Malicious assign parameters! (status = %s)", expr_status_to_string(status[1]));
					}

					gchar* result = var_replace_substrings(result_raw);

					var_set_value(varident, VAR_STRING, result);
					g_free(result_raw);
					g_free(result);
					break;
				}

				default: Error("Expression type %d not supported in assign statement!\n", expression->type);
			}

			g_free(varident);
			break;
		}

		case STMT_REPEAT: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* varident = param_string_get(paramList, 0, &status[0]);
			glong i, loopCount = param_int_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_REPEAT: variable = %s, loopCount = %ld", varident, loopCount);

			g_assert(loopCount >= 0);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious repeat parameters! (%s:%d)", __FILE__, __LINE__);
			}

			for (i=0; i<loopCount; i++) {
				var_set_value(varident, VAR_INT, &i);
				g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);
			}

			var_destroy(varident);
			g_free(varident);
			break;
		}

		case STMT_TIME: {
			Verbose("~ Executing STMT_TIME: label = %s", stmt->label);

			static gint timeId = 0;
			gdouble time;
			GTimer* timer = g_timer_new();

			g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);

			g_timer_stop(timer);
			time = g_timer_elapsed(timer, NULL);
			g_timer_destroy(timer);

			gchar* label = var_replace_substrings(stmt->label);
			timeList = g_slist_prepend(timeList, timeevent_new(timeId++, label, time));
			g_free(label);
			break;
		}

		case STMT_CTIME: {
			Verbose("~ Executing STMT_CTIME: label = %s", stmt->label);

			static gint coreTimeId = 0;
			gchar* label = var_replace_substrings(stmt->label);
			CoreTimeEvent* coreTimeEvent = coretime_event_new(coreTimeId++, label, coretime_new(0, 0));
			coreTimeStack = g_list_prepend(coreTimeStack, coreTimeEvent);

			g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);

			coreTimeList = g_slist_prepend(coreTimeList, coreTimeEvent);
			coreTimeStack = g_list_remove_link(coreTimeStack, g_list_first(coreTimeStack));
			g_free(label);
			break;
		}

#ifdef HAVE_MPI
		case STMT_GROUP: {
			Verbose("~ Executing STMT_GROUP: group = %s", stmt->label);

			GroupBlock* groupBlock = g_hash_table_lookup(groupMap, stmt->label);

			if(groupBlock && groupBlock->member) {
				groupStack = g_list_prepend(groupStack, groupBlock);
				g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);
				groupStack = g_list_remove_link(groupStack, g_list_first(groupStack));
			}
			else if(!groupBlock) {
				backtrace(stmt);
				Error("Group \"%s\" doesn't exist!", stmt->label);
			}
			break;
		}

		case STMT_MASTER: {
			GroupBlock* groupBlock;
			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack) {
				groupBlock = (GroupBlock*) g_list_first(groupStack)->data;
				comm = groupBlock->mpicomm;
			}

			gint groupRank;
			MPI_ASSERT(MPI_Comm_rank(comm, &groupRank), "Master Statement", TRUE)

			if(groupStack) Verbose("~ Executing STMT_MASTER: rank = %d, type = implicit group", groupRank);
			else           Verbose("~ Executing STMT_MASTER: rank = %d, type = world", groupRank);

			if(groupRank == MASTER) {
				g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);
			}
			else Verbose("Im not the master here... groupRank = %d", groupRank);
			break;
		}

		case STMT_BARRIER: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* groupName = param_string_get_optional(paramList, 0, &status[0], NULL);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			GroupBlock* groupBlock = groupblock_get(groupName);

			if(groupName)  Verbose("~ Executing STMT_BARRIER: type = explicit group, name = %s", groupName);
			else           Verbose("~ Executing STMT_BARRIER: type = implicit active group");

			MPI_ASSERT(MPI_Barrier(groupBlock->mpicomm), "Barrier Statement", TRUE)

			g_free(groupName);
			break;
		}
#endif

		case STMT_SLEEP: {
			if (agileMode) return;
			Verbose("~ Executing STMT_SLEEP");

			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			glong time = param_int_get(paramList, 0, &status[0]);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			g_usleep(time);
			//sleep(time);
			break;
		}

		case STMT_BLOCK: {
			Verbose("~ Executing STMT_BLOCK");
			g_node_children_foreach(node, G_TRAVERSE_ALL, &ExecuteStatement, NULL);
			break;
		}

		case STMT_PRINT: {
			Verbose("~ Executing STMT_PRINT");

			ParameterList* paramList = stmt->parameters;
			GString* buffer = g_string_new("");
			ExpressionStatus status;
			gint i;

			for (i=0; i<paramList->len; i++) {
				gchar* string = param_string_get(paramList, i, &status);
				if (status == STATUS_EVAL_OK) {
					g_string_append(buffer, string);
					g_free(string);
					if (i < (paramList->len-1))
						g_string_append(buffer, " ");
				}
				else {
					backtrace(stmt);
					Error("Error during print parameter evaluation (index=%d, status=%s).\n",
							i, expr_status_to_string(status));
				}
			}

			gchar* processed = var_replace_substrings(buffer->str);
			g_printf("[%d] %s\n", rank, processed);
			g_free(processed);
			g_string_free(buffer, TRUE);
			break;
		}

		case STMT_FCREAT: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* fhname = param_string_get(paramList, 0, &status[0]);
			gchar* fname_raw = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_FCREAT: fhname = %s, fname = %s", fhname, fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			File* file;
			IOStatus ioStatus = iio_fcreat(fname, &file);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success) {
				Verbose("  > file = %p", file);
				var_set_value(fhname, VAR_FILE, &file);
				statementsSucceed[STMT_FCREAT]++;
			}
			else
				statementsFail[STMT_FCREAT]++;

			g_free(fhname);
			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_FOPEN: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			gchar* fhname = param_string_get(paramList, 0, &status[0]);
			gchar* fname_raw = param_string_get(paramList, 1, &status[1]);
			gint   flags = param_int_get(paramList, 2, &status[2]);

			Verbose("~ Executing STMT_FOPEN: fhname = %s, fname = %s, flags = %d", fhname, fname_raw, flags);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			File* file;
			IOStatus ioStatus = iio_fopen(fname, flags, &file);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success) {
				Verbose("  > file = %p", file);
				var_set_value(fhname, VAR_FILE, &file);
				statementsSucceed[STMT_FOPEN]++;
			}
			else
				statementsFail[STMT_FOPEN]++;

			g_free(fhname);
			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_FCLOSE: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_FCLOSE: file = %p", file);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			g_assert(file);

			IOStatus ioStatus = iio_fclose(file);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success) {
				gchar* fhname = (gchar*) param_value_get(paramList, 0);
				var_destroy(fhname);
				statementsSucceed[STMT_FCLOSE]++;
			}
			else
				statementsFail[STMT_FCLOSE]++;
			break;
		}

		case STMT_FREAD: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);
			glong dataSize = param_int_get_optional(paramList, 1, &status[1], READALL);
			glong offset = param_int_get_optional(paramList, 2, &status[2], OFFSET_CUR);

			Verbose("~ Executing STMT_FREAD: file = %p, dataSize = %ld, offset = %ld", file, dataSize, offset);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			IOStatus ioStatus = iio_fread(file, dataSize, offset);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_FREAD]++;
			else
				statementsFail[STMT_FREAD]++;
			break;
		}

		case STMT_FWRITE: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);
			glong dataSize = param_int_get(paramList, 1, &status[1]);
			glong offset = param_int_get_optional(paramList, 2, &status[2], -1);

			Verbose("~ Executing STMT_FWRITE: file = %p, dataSize = %ld, offset = %ld", file, dataSize, offset);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			IOStatus ioStatus = iio_fwrite(file, dataSize, offset);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_FWRITE]++;
			else
				statementsFail[STMT_FWRITE]++;
			break;
		}

		case STMT_FSEEK: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);
			glong offset = param_int_get(paramList, 1, &status[1]);
			gint whence = param_int_get_optional(paramList, 2, &status[2], SEEK_SET);

			Verbose("~ Executing STMT_FSEEK: file = %p, offset = %ld, whence = %d", file, offset, whence);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			IOStatus ioStatus = iio_fseek(file, offset, whence);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_FSEEK]++;
			else
				statementsFail[STMT_FSEEK]++;
			break;
		}

		case STMT_FSYNC: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			IOStatus ioStatus = iio_fsync(file);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_FSYNC]++;
			else {
				statementsFail[STMT_FSYNC]++;
			}
			break;
		}

		case STMT_WRITE: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);
			glong  dataSize = param_int_get(paramList, 1, &status[1]);
			glong  offset = param_int_get_optional(paramList, 2, &status[2], 0);

			Verbose("~ Executing STMT_WRITE: file = %s, dataSize = %ld, offset = %ld", fname_raw, dataSize, offset);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_write(fname, dataSize, offset);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_WRITE]++;
			else
				statementsFail[STMT_WRITE]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_APPEND: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);
			glong  dataSize = param_int_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_APPEND: file = %s, dataSize = %ld", fname_raw, dataSize);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_append(fname, dataSize);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_APPEND]++;
			else
				statementsFail[STMT_APPEND]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_READ: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);
			glong  dataSize = param_int_get_optional(paramList, 1, &status[1], READALL);
			glong  offset = param_int_get_optional(paramList, 2, &status[2], 0);

			Verbose("~ Executing STMT_READ: file = %s, dataSize = %ld, offset = %ld",
					fname_raw, dataSize, offset);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_read(fname, dataSize, offset);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_READ]++;
			else
				statementsFail[STMT_READ]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_LOOKUP: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_LOOKUP: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_lookup(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_LOOKUP]++;
			else
				statementsFail[STMT_LOOKUP]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_DELETE: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_DELETE: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_delete(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_DELETE]++;
			else
				statementsFail[STMT_DELETE]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_MKDIR: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_MKDIR: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_mkdir(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_MKDIR]++;
			else
				statementsFail[STMT_MKDIR]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_RMDIR: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_RMDIR: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_rmdir(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_RMDIR]++;
			else
				statementsFail[STMT_RMDIR]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_CREATE: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_CREATE: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_create(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_CREATE]++;
			else
				statementsFail[STMT_CREATE]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_STAT: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_STAT: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			IOStatus ioStatus = iio_stat(fname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_STAT]++;
			else
				statementsFail[STMT_STAT]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}

		case STMT_RENAME: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* oldname_raw = param_string_get(paramList, 0, &status[0]);
			gchar* newname_raw = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_RENAME: oldname = %s, newname = %s", oldname_raw, oldname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* oldname = var_replace_substrings(oldname_raw);
			gchar* newname = var_replace_substrings(newname_raw);

			IOStatus ioStatus = iio_rename(oldname, newname);
			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_RENAME]++;
			else
				statementsFail[STMT_RENAME]++;

			g_free(oldname_raw);
			g_free(newname_raw);
			g_free(oldname);
			g_free(newname);
			break;
		}

#ifdef HAVE_MPI
		case STMT_PFOPEN: {
			ExpressionStatus status[3];
			ParameterList* paramList = stmt->parameters;
			gchar* fhname = param_string_get(paramList, 0, &status[0]);
			gchar* fname_raw = param_string_get(paramList, 1, &status[1]);
			gchar* mode = param_string_get(paramList, 2, &status[2]);

			Verbose("~ Executing STMT_FOPEN: fhname = %s, fname = %s mode = %s", fhname, fname_raw, mode);

			// evaluator error check
			if (!expr_status_assert(status, 3)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);
			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack)
				comm = ((GroupBlock*) g_list_first(groupStack)->data)->mpicomm;

			File* file;
			if (iio_pfopen(fname, mode, comm, &file)) {
				Verbose("  > file = %p", file);
				var_set_value(fhname, VAR_FILE, &file);
				statementsSucceed[STMT_PFOPEN]++;
			}
			else
				statementsFail[STMT_PFOPEN]++;

			g_free(fhname);
			g_free(fname_raw);
			g_free(fname);
			g_free(mode);
			break;
		}

		case STMT_PFCLOSE: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			File* file = param_file_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_FCLOSE: file = %p", file);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			if (file && iio_pfclose(file)) {
				gchar* fhname = (gchar*) param_value_get(paramList, 0);
				var_destroy(fhname);
				statementsSucceed[STMT_PFCLOSE]++;
			}
			else
				statementsFail[STMT_PFCLOSE]++;
			break;
		}

		case STMT_PFWRITE: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			File*  file = param_file_get(paramList, 0, &status[0]);
			gchar* pname = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_PFWRITE: file = %p, pattern = %s", file, pname);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			Pattern* pattern = g_hash_table_lookup(patternMap, pname);
			if (!pattern) {
				g_printf("Invalid pattern parameter in statement pfwrite.\n");
				Error("Malicious statement parameters!");
				break;
			}

			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack)
				comm = ((GroupBlock*) g_list_first(groupStack)->data)->mpicomm;

			IOStatus ioStatus;
			switch(pattern->level) {
				/* Level 0: non-collective, contiguous */
				case 0:
					Verbose("  > level = 0");
					ioStatus = iio_pfwrite_level0(file, pattern);
					break;

				/* Level 1: collective, contiguous */
				case 1:
					Verbose("  > level = 1");
					ioStatus = iio_pfwrite_level1(file, pattern);
					break;

				/* Level 2: non-collective, non-contiguous */
				case 2:
					Verbose("  > level = 2");
					ioStatus = iio_pfwrite_level2(file, pattern);
					break;

				/* Level 3: collective, non-contiguous */
				case 3:
					Verbose("  > level = 3");
					ioStatus = iio_pfwrite_level3(file, pattern);
					break;

				default: Error("Invalid level (%d) for statement pfwrite!", pattern->level);
			}

			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_PFWRITE]++;
			else
				statementsFail[STMT_PFWRITE]++;

			g_free(pname);
			break;
		}

		case STMT_PFREAD: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			File*  file = param_file_get(paramList, 0, &status[0]);
			gchar* pname = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_PFREAD: file = %p, pattern = %s", file, pname);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			Pattern* pattern = g_hash_table_lookup(patternMap, pname);
			if (!pattern) {
				g_printf("Invalid pattern parameter in statement pread.\n");
				Error("Malicious statement parameters!");
				break;
			}

			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack)
				comm = ((GroupBlock*) g_list_first(groupStack)->data)->mpicomm;

			IOStatus ioStatus;
			switch(pattern->level) {
				/* Level 0: non-collective, contiguous */
				case 0:
					Verbose("  > level = 0");
					ioStatus = iio_pfread_level0(file, pattern);
					break;

				/* Level 1: collective, contiguous */
				case 1:
					Verbose("  > level = 1");
					ioStatus = iio_pfread_level1(file, pattern);
					break;

				/* Level 2: non-collective, non-contiguous */
				case 2:
					Verbose("  > level = 2");
					ioStatus = iio_pfread_level2(file, pattern);
					break;

				/* Level 3: collective, non-contiguous */
				case 3:
					Verbose("  > level = 3");
					ioStatus = iio_pfread_level3(file, pattern);
					break;

				default: Error("Invalid level (%d) for statement pfread!", pattern->level);
			}

			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_PFREAD]++;
			else
				statementsFail[STMT_PFREAD]++;

			g_free(pname);
			break;
		}

		case STMT_PWRITE: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);
			gchar* pname = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_PWRITE: file = %s, pattern = %s", fname_raw, pname);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			Pattern* pattern = g_hash_table_lookup(patternMap, pname);
			if (!pattern) {
				g_printf("Invalid pattern parameter in statement pwrite.\n");
				Error("Malicious statement parameters!");
				break;
			}

			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack)
				comm = ((GroupBlock*) g_list_first(groupStack)->data)->mpicomm;

			IOStatus ioStatus;
			switch(pattern->level) {
				/* Level 0: non-collective, contiguous */
				case 0:
					Verbose("  > level = 0");
					ioStatus = iio_pwrite_level0(fname, pattern, comm);
					break;

				/* Level 1: collective, contiguous */
				case 1:
					Verbose("  > level = 1");
					ioStatus = iio_pwrite_level1(fname, pattern, comm);
					break;

				/* Level 2: non-collective, non-contiguous */
				case 2:
					Verbose("  > level = 2");
					ioStatus = iio_pwrite_level2(fname, pattern, comm);
					break;

				/* Level 3: collective, non-contiguous */
				case 3:
					Verbose("  > level = 3");
					ioStatus = iio_pwrite_level3(fname, pattern, comm);
					break;

				default: Error("Invalid level (%d) for statement pwrite!", pattern->level);
			}

			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_PWRITE]++;
			else
				statementsFail[STMT_PWRITE]++;

			g_free(fname_raw);
			g_free(fname);
			g_free(pname);
			break;
		}

		case STMT_PREAD: {
			ExpressionStatus status[2];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);
			gchar* pname = param_string_get(paramList, 1, &status[1]);

			Verbose("~ Executing STMT_PREAD: file = %s, pattern = %s", fname_raw, pname);

			// evaluator error check
			if (!expr_status_assert(status, 2)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			Pattern* pattern = g_hash_table_lookup(patternMap, pname);
			if (!pattern) {
				g_printf("Invalid pattern parameter in statement pread.\n");
				g_free(fname);
				Error("Malicious statement parameters!");
				break;
			}

			MPI_Comm comm = MPI_COMM_WORLD;
			if(groupStack)
				comm = ((GroupBlock*) g_list_first(groupStack)->data)->mpicomm;

			IOStatus ioStatus;
			switch(pattern->level) {
				/* Level 0: non-collective, contiguous */
				case 0:
					Verbose("  > level = 0");
					ioStatus = iio_pread_level0(fname, pattern, comm);
					break;

				/* Level 1: collective, contiguous */
				case 1:
					Verbose("  > level = 1");
					ioStatus = iio_pread_level1(fname, pattern, comm);
					break;

				/* Level 2: non-collective, non-contiguous */
				case 2:
					Verbose("  > level = 2");
					ioStatus = iio_pread_level2(fname, pattern, comm);
					break;

				/* Level 3: collective, non-contiguous */
				case 3:
					Verbose("  > level = 3");
					ioStatus = iio_pread_level3(fname, pattern, comm);
					break;

				default: Error("Invalid level (%d) for statement pread!", pattern->level);
			}

			dump_coretime(coreTimeStack, ioStatus.coreTime);

			if (ioStatus.success)
				statementsSucceed[STMT_PREAD]++;
			else
				statementsFail[STMT_PREAD]++;

			g_free(fname_raw);
			g_free(fname);
			g_free(pname);
			break;
		}

		case STMT_PDELETE: {
			ExpressionStatus status[1];
			ParameterList* paramList = stmt->parameters;
			gchar* fname_raw = param_string_get(paramList, 0, &status[0]);

			Verbose("~ Executing STMT_PDELETE: file = %s", fname_raw);

			// evaluator error check
			if (!expr_status_assert(status, 1)) {
				backtrace(stmt);
				Error("Malicious statement parameters!");
			}

			gchar* fname = var_replace_substrings(fname_raw);

			if (iio_pdelete(fname))
				statementsSucceed[STMT_PDELETE]++;
			else
				statementsFail[STMT_PDELETE]++;

			g_free(fname_raw);
			g_free(fname);
			break;
		}
#endif

		/* ![ModuleHook] statement_exec */

		default: Error("Invalid statement! (id=%d)\n", stmt->type);
	}
}
示例#10
0
文件: grab.c 项目: saisasidhar/libuca
static GError *
record_frames (UcaCamera *camera, Options *opts)
{
    guint roi_width;
    guint roi_height;
    guint bits;
    guint pixel_size;
    gsize size;
    gint n_frames;
    guint n_allocated;
    GTimer *timer;
    UcaRingBuffer *buffer;
    GError *error = NULL;
    gdouble last_printed;

    g_object_get (G_OBJECT (camera),
                  "roi-width", &roi_width,
                  "roi-height", &roi_height,
                  "sensor-bitdepth", &bits,
                  NULL);

    pixel_size = get_bytes_per_pixel (bits);
    size = roi_width * roi_height * pixel_size;
    n_allocated = opts->n_frames > 0 ? opts->n_frames : 256;
    buffer = uca_ring_buffer_new (size, n_allocated);
    timer = g_timer_new();

    g_print("Start recording: %ix%i at %i bits/pixel\n",
            roi_width, roi_height, bits);

    uca_camera_start_recording(camera, &error);

    if (error != NULL)
        return error;

    n_frames = 0;
    g_timer_start(timer);
    last_printed = 0.0;

    while (1) {
        gdouble elapsed;

        uca_camera_grab (camera, uca_ring_buffer_get_write_pointer (buffer), &error);
        uca_ring_buffer_write_advance (buffer);

        if (error != NULL)
            return error;

        n_frames++;
        elapsed = g_timer_elapsed (timer, NULL);

        if (n_frames == opts->n_frames || (opts->duration > 0.0 && elapsed >= opts->duration))
            break;

        if (elapsed - last_printed >= 1.0) {
            g_print ("Recorded %i frames at %.2f frames/s\n",
                     n_frames, n_frames / elapsed);
            last_printed = elapsed;
        }
    }

    g_print ("Stop recording: %3.2f frames/s\n",
             n_frames / g_timer_elapsed (timer, NULL));

    uca_camera_stop_recording (camera, &error);

#ifdef HAVE_LIBTIFF
    if (opts->write_tiff)
        write_tiff (buffer, opts, roi_width, roi_height, bits);
    else
        write_raw (buffer, opts);
#else
    write_raw (buffer, opts);
#endif

    g_object_unref (buffer);
    g_timer_destroy (timer);

    return error;
}
示例#11
0
文件: cartesian.c 项目: Gilles86/afni
int main (int argc, char * argv[])
{
  guint i, j, nx, ny;
  gdouble cosa, sina;
  GtsSurface * surface;
  GSList * l, * vertices = NULL;
  GtsTriangle * t;
  GtsVertex * v1, * v2, * v3;
  GTimer * timer;

  if (argc != 4) {
    fprintf (stderr, "usage: cartesian nx ny angle\n");
    return 0;
  }

  nx = atoi (argv[1]);
  ny = atoi (argv[2]);
  cosa = cos (atof (argv[3]));
  sina = sin (atof (argv[3]));

  timer = g_timer_new ();
  g_timer_start (timer);
  for (i = 0; i < nx; i++) {
    gdouble x = (gdouble) i/(gdouble) (nx - 1); 
    for (j = 0; j < ny; j++) {
      gdouble y = (gdouble) j/(gdouble) (nx - 1); 
      vertices = g_slist_prepend (vertices, 
		     gts_vertex_new (gts_vertex_class (),
				     cosa*x - sina*y, sina*x + cosa*y, 0.));
    }
  }

  t = gts_triangle_enclosing (gts_triangle_class (), vertices, 100.);
  gts_triangle_vertices (t, &v1, &v2, &v3);
  surface = gts_surface_new (gts_surface_class (),
			     gts_face_class (),
			     gts_edge_class (),
			     gts_vertex_class ());
  gts_surface_add_face (surface, gts_face_new (gts_face_class (),
					       t->e1, t->e2, t->e3));
  g_timer_stop (timer);
  fprintf (stderr, "Input: %g s\n", g_timer_elapsed (timer, NULL));
  g_timer_reset (timer);

  g_timer_start (timer);
  l = vertices;
  while (l) {
    g_assert (gts_delaunay_add_vertex (surface, l->data, NULL) == NULL);
    l = l->next;
  }

  gts_allow_floating_vertices = TRUE;
  gts_object_destroy (GTS_OBJECT (v1));
  gts_object_destroy (GTS_OBJECT (v2));
  gts_object_destroy (GTS_OBJECT (v3));
  gts_allow_floating_vertices = FALSE;
  g_timer_stop (timer);

  fprintf (stderr, "Triangulation: %g s speed: %.0f vertex/s\n", 
	   g_timer_elapsed (timer, NULL),
	   g_slist_length (vertices)/g_timer_elapsed (timer, NULL));
  g_timer_reset (timer);

  g_timer_start (timer);
  gts_surface_write (surface, stdout);
  g_timer_stop (timer);

  fprintf (stderr, "Output: %g s\n", g_timer_elapsed (timer, NULL));

  if (gts_delaunay_check (surface)) {
    fprintf (stderr, "WARNING: surface is not Delaunay\n");
    return 0;
  }

  return 1;
}
示例#12
0
int go_to_bookmark(const char *link)
{
#ifdef __WIN32__
	HINSTANCE hInst;

	// Windows do the whole work for us, let's go...
	hInst = ShellExecute(NULL, "open", link, NULL, NULL, SW_SHOWNORMAL);
	if((int)hInst <= 32)
	{
		//msg_box("Error", "Unable to run ShellExecute extension.");
		return -1;
	}
#else
	// Kevin's list:
	// These ones should be first, as they will honor the user's choice rather
	// than guessing an arbitrary one:
	// * /usr/bin/xdg-open (runs the default browser of the desktop environment
	// currently in use, this is the best solution)
	// * /usr/bin/gnome-open (GNOME 2.6+ default browser, user-configurable)
	// Distro-specific browser wrapper scripts:
	// * /usr/bin/sensible-browser (Debian's browser script)
	// * /usr/bin/htmlview (old RHL/Fedora default browser script, current
	// versions will honor the GNOME browser preference)
	// Fallback to a hardcoded list of browsers:
	// * /usr/bin/firefox (Mozilla Firefox)
	// * /usr/bin/seamonkey (Seamonkey)
	// * /usr/bin/konqueror (Konqueror)
	// * /usr/bin/mozilla (old Mozilla Suite)
	//
	gboolean result;
	static const char *apps[] = { 
			"/usr/bin/xdg-open",
			"/usr/bin/gnome-open",
			"/usr/bin/sensible-browser",
			"/usr/bin/htmlview",
			"/usr/bin/firefox",
			"/usr/bin/seamonkey",
			"/usr/bin/konqueror",
			"/usr/bin/mozilla",
	};
	gint i, n;

	n = sizeof(apps) / sizeof(apps[0]);
	for(i = 0; i < n; i++)
	{
		gchar **argv = g_malloc0(3 * sizeof(gchar *));

		argv[0] = g_strdup(apps[i]);
		argv[1] = g_strdup(link);
		argv[2] = NULL;

		result = g_spawn_async(NULL, argv, NULL, 0, NULL, NULL, NULL, NULL);
		g_strfreev(argv);

		if(result != FALSE)
			break;
	}

	if (i == n) 
	{
		msg_box1("Error", "Spawn error: do you have Firefox installed ?");
		return -1;
	} 
#endif
	else 
	{
		const gchar *message = _("A web browser has been launched: this may take a while before it appears. If it is already launched, the page may be opened in the existing frame.");
		GTimer *timer;

		msg_box("Information", message, !0);

		for(timer = g_timer_new(); g_timer_elapsed(timer, NULL) < 3.0;);
		g_timer_destroy(timer);

		msg_box("", "", 0);
	}

	return 0;
}
int
main (int argc, char *argv[])
{
	CORBA_Object obj;
	CORBA_Environment ev;
        Bonobo_ServerInfoList *info;
        CORBA_Object ac;
        char *sort_by[4];
        char *query;
        int   i;
        GTimer *timer = g_timer_new ();
	Bonobo_EventSource event_source;
	
        g_thread_init (NULL);

	CORBA_exception_init (&ev);

        bonobo_activation_object_directory_get (
                bonobo_activation_username_get (),
                bonobo_activation_hostname_get ());

	bonobo_init (&argc, argv);
/*      putenv("Bonobo_BARRIER_INIT=1"); */


	event_source = bonobo_activation_activate_from_id
                ("OAFIID:Bonobo_Activation_EventSource", 0, NULL, &ev);
        if (event_source != CORBA_OBJECT_NIL) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: Activation event source okay\n",
                         passed + failed, TOTAL_TEST_SCORE);
   	        bonobo_event_source_client_add_listener (event_source, listener_cb,
                                                         "Bonobo/ObjectDirectory", &ev, NULL);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Activation event source not found\n",
                         passed + failed, TOTAL_TEST_SCORE);
	}


        race_base_init ();

        sort_by[0] = "prefer_by_list_order(iid, ["
                "'OAFIID:nautilus_file_manager_icon_view:42681b21-d5ca-4837-87d2-394d88ecc058',"
                "'OAFIID:nautilus_file_manager_list_view:521e489d-0662-4ad7-ac3a-832deabe111c',"
                "'OAFIID:nautilus_music_view:9456b5d2-60a8-407f-a56e-d561e1821391'])";
        sort_by[1] = "iid != 'OAFIID:nautilus_content_loser:95901458-c68b-43aa-aaca-870ced11062d'";
        sort_by[2] = "iid != 'OAFIID:nautilus_sample_content_view:45c746bc-7d64-4346-90d5-6410463b43ae'";
        sort_by[3] = NULL;

        query = "( (((repo_ids.has_all (['IDL:Bonobo/Control:1.0',"
                "'IDL:Nautilus/View:1.0']) OR (repo_ids.has_one "
                "(['IDL:Bonobo/Control:1.0','IDL:Bonobo/Embeddable:1.0']) AND "
                "repo_ids.has_one (['IDL:Bonobo/PersistStream:1.0', "
                "'IDL:Bonobo/ProgressiveDataSink:1.0', "
                "'IDL:Bonobo/PersistFile:1.0']))) AND (bonobo:supported_mime_types.defined () OR "
                "bonobo:supported_uri_schemes.defined () OR "
                "bonobo:additional_uri_schemes.defined ()) AND "
                "(((NOT bonobo:supported_mime_types.defined () OR "
                "bonobo:supported_mime_types.has ('x-directory/normal') OR "
                "bonobo:supported_mime_types.has ('x-directory/*') OR "
                "bonobo:supported_mime_types.has ('*/*')) AND "
                "(NOT bonobo:supported_uri_schemes.defined () OR "
                "bonobo:supported_uri_schemes.has ('file') OR "
                "bonobo:supported_uri_schemes.has ('*'))) OR "
                "(bonobo:additional_uri_schemes.has ('file') OR "
                "bonobo:additional_uri_schemes.has ('*'))) AND "
                "nautilus:view_as_name.defined ()) OR false) AND "
                "(has (['OAFIID:nautilus_file_manager_icon_view:42681b21-d5ca-4837-87d2-394d88ecc058', "
                "'OAFIID:nautilus_file_manager_list_view:521e489d-0662-4ad7-ac3a-832deabe111c'], iid)) ) AND "
                "(NOT test_only.defined() OR NOT test_only)";

        ac = bonobo_activation_activation_context_get ();

        g_timer_start (timer);

        info = bonobo_activation_query (query, sort_by, &ev);

        for (i = 0; i < 1000; i++) {
                Bonobo_ServerInfoList *copy;
                copy = Bonobo_ServerInfoList_duplicate (info);
                CORBA_free (copy);
        }
        g_timer_stop (timer);

        fprintf (stderr, "Time to query '%g'\n", g_timer_elapsed (timer, NULL));
        if (ev._major == CORBA_NO_EXCEPTION) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: timed query\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: timed query\n", passed + failed, TOTAL_TEST_SCORE);
                CORBA_exception_free (&ev);
	}

        /*
         *    We wait to see if the server (sever)
         * timeout is mis-behaving [ at this stage we
         * have not registered anything with the server ]
         */
        fprintf (stderr, "Waiting to see if the server erroneously quits\n");
        g_usleep (SERVER_IDLE_QUIT_TIMEOUT * 2 * 1000);
        g_assert (ORBit_small_get_connection_status (ac) ==
                  ORBIT_CONNECTION_CONNECTED);

        race_empty (&ev);
	
	
	
	

	obj = bonobo_activation_activate_from_id ("OAFIID:Empty:19991025", 0, NULL, &ev);
        if (test_object (obj, &ev, "from id") && test_empty (obj, &ev, "from id")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: IID activation\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: IID activation\n", passed + failed, TOTAL_TEST_SCORE);
	}

	obj = bonobo_activation_activate_from_id ("OAFAID:[OAFIID:Empty:19991025]", 0, NULL, &ev);
        if (test_object (obj, &ev, "from aid") && test_empty (obj, &ev, "from aid")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: AID activation\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: AID activation\n", passed + failed, TOTAL_TEST_SCORE);
	}

	obj = bonobo_activation_activate_from_id ("OAFAID:[OAFIID:Plugin:20010713]",  0, NULL, &ev);
	if (test_object (obj, &ev, "from aid") && test_plugin (obj, &ev, "from aid")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: plugin activation\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: plugin activation\n", passed + failed, TOTAL_TEST_SCORE);
	}

        obj = bonobo_activation_activate_from_id ("OAFIID:Bogus:20000526", 0, NULL, &ev);
        if (ev._major != CORBA_NO_EXCEPTION) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: Broken link test : %s\n",
			 passed + failed, TOTAL_TEST_SCORE, bonobo_activation_exception_id (&ev));
                CORBA_exception_free (&ev);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Broken link test\n", passed + failed, TOTAL_TEST_SCORE);
	}

        if (test_bonobo_activation_server (&ev, "with broken factory link")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
	}

        fprintf (stderr, "Broken exe test ");
        obj = bonobo_activation_activate_from_id ("OAFIID:Broken:20000530", 0, NULL, &ev);
        if (ev._major != CORBA_NO_EXCEPTION) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: Broken exe test : %s\n",
			 passed + failed, TOTAL_TEST_SCORE, bonobo_activation_exception_id (&ev));
                CORBA_exception_free (&ev);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Broken exe test\n", passed + failed, TOTAL_TEST_SCORE);
	}

        if (test_bonobo_activation_server (&ev, "with broken factory link")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
	}

        obj = bonobo_activation_activate_from_id ("OAFIID:Circular:20000530", 0, NULL, &ev);
        if (ev._major != CORBA_NO_EXCEPTION) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: Circular link test : %s\n",
			 passed + failed, TOTAL_TEST_SCORE, bonobo_activation_exception_id (&ev));
                CORBA_exception_free (&ev);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Circular link test\n", passed + failed, TOTAL_TEST_SCORE);
	}

        if (test_bonobo_activation_server (&ev, "with broken factory link")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
	}

        obj = bonobo_activation_activate_from_id ("OAFIID:NotInServer:20000717", 0, NULL, &ev);
        if (ev._major != CORBA_NO_EXCEPTION) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: Server that doesn't register IID test : %s\n",
			 passed + failed, TOTAL_TEST_SCORE, bonobo_activation_exception_id (&ev));
                CORBA_exception_free (&ev);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Server that doesn't register IID test\n",
			 passed + failed, TOTAL_TEST_SCORE);
	}

        if (test_bonobo_activation_server (&ev, "with non-registering server")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
	}

        obj = bonobo_activation_activate_from_id ("OAFIID:BrokenNoType:20000808", 0, NULL, &ev);
        if (ev._major != CORBA_NO_EXCEPTION) {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Server with IID but no type or location : %s\n",
			 passed + failed, TOTAL_TEST_SCORE, bonobo_activation_exception_id (&ev));
                CORBA_exception_free (&ev);
        } else if (obj) {
		failed++;
		fprintf (stderr, "FAILED %d of %d: Server with IID but no type or location\n",
			 passed + failed, TOTAL_TEST_SCORE);
        } else {
                passed++;
		fprintf (stderr, "PASSED %d of %d: Server with IID but no type or location\n",
			 passed + failed, TOTAL_TEST_SCORE);
        }

        if (test_bonobo_activation_server (&ev, "with no-type/loc server")) {
		passed++;
		fprintf (stderr, "PASSED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
        } else {
		failed++;
		fprintf (stderr, "FAILED %d of %d: activation server okay\n", passed + failed, TOTAL_TEST_SCORE);
	}

        fprintf (stderr, "\n%d of %d tests passed (%s)\n", passed,
                 TOTAL_TEST_SCORE,
                 passed == TOTAL_TEST_SCORE? "All": "some failures");

        if (passed < (TOTAL_TEST_SCORE * 2 / 3)) {
                fprintf (stderr, "It looks like you have not installed broken.server "
                         "into ${prefix}/share/bonobo-activation/, this must be done "
                         "by hand to avoid problems with normal operation.\n");
		fprintf (stderr, "Another possibility is that you failed to kill "
			 "bonobo_activation_server before running make check; try running bonobo-slay.\n");
        }

        if (name_service != CORBA_OBJECT_NIL)
                CORBA_Object_release (name_service, &ev);
        
        if (event_source != CORBA_OBJECT_NIL)
		CORBA_Object_release (event_source, &ev);

	CORBA_exception_free (&ev);

        if (passed == TOTAL_TEST_SCORE) {
                if (bonobo_debug_shutdown ()) {
                        return 0;
                } else {
                        return 1;
                }
        } else {
                return 1;
        }
}
示例#14
0
int main(int argc, char *argv[])
{
	struct sigaction sa;
	GDHCPClientError error;
	GDHCPClient *dhcp_client;
	int index;

	if (argc < 2) {
		printf("Usage: dhcp-test <interface index>\n");
		exit(0);
	}

	index = atoi(argv[1]);

	printf("Create DHCP client for interface %d\n", index);

	dhcp_client = g_dhcp_client_new(G_DHCP_IPV4, index, &error);
	if (dhcp_client == NULL) {
		handle_error(error);
		exit(0);
	}

	g_dhcp_client_set_send(dhcp_client, G_DHCP_HOST_NAME, "<hostname>");

	g_dhcp_client_set_request(dhcp_client, G_DHCP_HOST_NAME);
	g_dhcp_client_set_request(dhcp_client, G_DHCP_SUBNET);
	g_dhcp_client_set_request(dhcp_client, G_DHCP_DNS_SERVER);
	g_dhcp_client_set_request(dhcp_client, G_DHCP_DOMAIN_NAME);
	g_dhcp_client_set_request(dhcp_client, G_DHCP_NTP_SERVER);
	g_dhcp_client_set_request(dhcp_client, G_DHCP_ROUTER);

	g_dhcp_client_register_event(dhcp_client,
			G_DHCP_CLIENT_EVENT_LEASE_AVAILABLE,
						lease_available_cb, NULL);

	g_dhcp_client_register_event(dhcp_client,
			G_DHCP_CLIENT_EVENT_NO_LEASE, no_lease_cb, NULL);

	main_loop = g_main_loop_new(NULL, FALSE);

	printf("Start DHCP operation\n");

	timer = g_timer_new();

	g_dhcp_client_start(dhcp_client, NULL);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sig_term;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	g_main_loop_run(main_loop);

	g_timer_destroy(timer);

	g_dhcp_client_unref(dhcp_client);

	g_main_loop_unref(main_loop);

	return 0;
}
示例#15
0
gboolean
run_command (TestProfile *tp, int zlevel, int slevel, File* from, File* to, File* out, File *re, gboolean accounting)
{
  int pid, status, outfd;
  struct stat sbuf;
  char xdelta_args[16];
  char xdelta_args2[16];
  char diff_gzargs[16];
  char gzip_args[16];

  GTimer *timer = g_timer_new ();

  sprintf (xdelta_args, "-qn%d", zlevel);
  sprintf (xdelta_args2, "-s%d", slevel);
  sprintf (diff_gzargs, "wb%d", zlevel);
  sprintf (gzip_args, "-c%d", zlevel);

  unlink (out->name);

  g_timer_start (timer);

  if ((pid = vfork()) < 0)
    return FALSE;

  if (pid == 0)
    {
      if (starts_with (tp->name, "xdelta"))
	{
	  execl (tp->progname,
		 tp->progname,
		 "delta",
		 xdelta_args,
		 xdelta_args2,
		 from->name,
		 to->name,
		 out->name,
		 NULL);
	}
      else
	{
	  outfd = open (out->name, O_CREAT | O_TRUNC | O_WRONLY, 0777);

	  if (outfd < 0)
	    {
	      perror ("open");
	      fail ();
	    }

	  dup2(outfd, STDOUT_FILENO);

	  if (close (outfd))
	    {
	      perror ("close");
	      fail ();
	    }

	  if (starts_with (tp->name, "diff"))
	    execl (tp->progname,
		   tp->progname,
		   "--rcs",
		   "-a",
		   from->name,
		   to->name,
		   NULL);
	  else if (starts_with (tp->name, "gzip"))
	    execl (tp->progname,
		   tp->progname,
		   gzip_args,
		   to->name,
		   NULL);
	  else
	    abort ();
	}

      perror ("execl failed");
      _exit (127);
    }

  if (waitpid (pid, &status, 0) != pid)
    {
      perror ("wait failed");
      fail ();
    }

  // Note: program is expected to return 0, 1 meaning diff or no diff,
  // > 1 indicates failure
  if (! WIFEXITED (status) || WEXITSTATUS (status) > 1)
    {
      g_warning ("delta command failed\n");
      fail ();
    }

  if (stat (out->name, & sbuf))
    {
      perror ("stat");
      fail ();
    }

  // Do zlib compression on behalf of diff
  if (zlevel > 0 && starts_with (tp->name, "diff"))
    {
      Patch  *patch   = read_patch (out, & sbuf);
      gzFile *rewrite = gzopen (out->name, diff_gzargs);

      if (! rewrite) fail ();

      if (gzwrite (rewrite, patch->data, patch->length) == 0) { perror ("gzwrite"); fail (); }
      if (gzclose (rewrite) != Z_OK)                          { perror ("gzclose"); fail (); }
      if (stat    (out->name, & sbuf))                        { perror ("stat");    fail (); }
    }

  g_timer_stop (timer);

  if (accounting)
    {
      add_tv (timer);
    }

  if (__dsize < 0)
    {
      __dsize = sbuf.st_size;

      // Verify only once

      if (starts_with (tp->name, "xdelta"))
	{
	  if (! xdelta_verify (tp, zlevel, slevel, from, to, out, re))
	    {
	      g_warning ("verify failed");
	      fail ();
	    }
	}
    }
  else
    {
      if (__dsize != sbuf.st_size)
	{
	  g_warning ("%s -%d: delta command produced different size deltas: %d and %d",
		     tp->progname, zlevel, (int)__dsize, (int)sbuf.st_size);
	  fail ();
	}
    }

  g_timer_destroy (timer);

  return TRUE;
}
示例#16
0
gboolean yfTimeOutFlush(
    yfContext_t        *ctx,
    uint32_t           pcap_drop,
    uint32_t           *total_stats,
    GTimer             *timer, /* yaf process timer */
    GTimer             *stats_timer, /* yaf stats output timer */
    GError             **err)
{
    AirLock             *lock = NULL;
    uint64_t            cur_time;

    /* point to lock buffer if we need it */
    if (ctx->cfg->lockmode) {
        lock = &ctx->lockbuf;
    }

    /* Open output if we need to */
    if (!ctx->fbuf) {
        if (!(ctx->fbuf = yfOutputOpen(ctx->cfg, lock, err))) {
            return FALSE;
        }
    }

    /* Dump statistics if requested */
    yfStatDumpLoop();

    /* Flush the flow table */
    if (!yfFlowTabFlush(ctx, FALSE, err)) {
        return FALSE;
    }

    if (!ctx->cfg->nostats) {
        if (!stats_timer) {
            stats_timer = g_timer_new();
        }
        if (g_timer_elapsed(stats_timer, NULL) > ctx->cfg->stats) {
            if (!yfWriteStatsFlow(ctx, pcap_drop, timer, err)) {
                return FALSE;
            }
            g_timer_start(stats_timer);
            *total_stats += 1;
        }
    }

    if (!fBufEmit(ctx->fbuf, err)) {
        return FALSE;
    }

    /* Close output file for rotation if necessary */
    if (ctx->cfg->rotate_ms) {
        cur_time = yfFlowTabCurrentTime(ctx->flowtab);
        if (ctx->last_rotate_ms) {
            if (cur_time - ctx->last_rotate_ms > ctx->cfg->rotate_ms) {
                yfOutputClose(ctx->fbuf, lock, TRUE);
                ctx->fbuf = NULL;
                ctx->last_rotate_ms = cur_time;
            }
        } else {
            ctx->last_rotate_ms = cur_time;
        }
    }

    return TRUE;
}
int
main (int argc, char *argv[])
{
	GtkSourceBuffer *buffer;
	GtkSourceSearchContext *search_context;
	GtkSourceSearchSettings *search_settings;
	GtkTextIter iter;
	GtkTextIter match_end;
	GTimer *timer;
	gint i;
	GtkTextSearchFlags flags;
	gchar *regex_pattern;

	gtk_init (&argc, &argv);

	buffer = gtk_source_buffer_new (NULL);

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	for (i = 0; i < NB_LINES; i++)
	{
		gtk_text_buffer_insert (GTK_TEXT_BUFFER (buffer),
					&iter,
					"A line of text to fill the text buffer. Is it long enough?\n",
					-1);
	}

	gtk_text_buffer_insert (GTK_TEXT_BUFFER (buffer), &iter, "foo\n", -1);

	/* Basic search, no flags */

	timer = g_timer_new ();

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	flags = 0;

	while (gtk_text_iter_forward_search (&iter, "foo", flags, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("basic forward search, no flags: %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Basic search, with flags always enabled by gsv */

	g_timer_start (timer);

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;

	while (gtk_text_iter_forward_search (&iter, "foo", flags, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("basic forward search, visible and text only flags: %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Basic search, with default flags in gsv */

	g_timer_start (timer);

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	flags = GTK_TEXT_SEARCH_VISIBLE_ONLY |
		GTK_TEXT_SEARCH_TEXT_ONLY |
		GTK_TEXT_SEARCH_CASE_INSENSITIVE;

	while (gtk_text_iter_forward_search (&iter, "foo", flags, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("basic forward search, all flags: %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Smart forward search, with default flags in gsv */

	search_settings = gtk_source_search_settings_new ();
	search_context = gtk_source_search_context_new (buffer, search_settings);

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, "foo");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("smart synchronous forward search, case insensitive: %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Smart forward search, case sensitive */

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, NULL);
	gtk_source_search_settings_set_case_sensitive (search_settings, TRUE);
	gtk_source_search_settings_set_search_text (search_settings, "foo");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("smart synchronous forward search, case sensitive: %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Regex search: search "foo" */

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, NULL);
	gtk_source_search_settings_set_regex_enabled (search_settings, TRUE);
	gtk_source_search_settings_set_search_text (search_settings, "foo");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("regex search: 'foo' (no partial matches): %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Regex search: search "fill" */

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, "fill");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("regex search: 'fill' (no partial matches): %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Regex search: search single lines */

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, ".*");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("regex search: match single lines (no partial matches): %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Regex search: search matches of 3 lines */

	g_timer_start (timer);

	/* The space at the beginning of the pattern permits to not have contiguous
	 * matches. There is a performance issue with contiguous matches.
	 */
	gtk_source_search_settings_set_search_text (search_settings, " (.*\n){3}");

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("regex search: matches of 3 lines (small partial matches): %lf seconds.\n",
		 g_timer_elapsed (timer, NULL));

	/* Regex search: search matches of really big chunks */

	g_timer_start (timer);

	regex_pattern = g_strdup_printf (" (.*\n){%d}", NB_LINES / 10);
	gtk_source_search_settings_set_search_text (search_settings, regex_pattern);
	g_free (regex_pattern);

	gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (buffer), &iter);

	while (gtk_source_search_context_forward (search_context, &iter, NULL, &match_end, NULL))
	{
		iter = match_end;
	}

	g_timer_stop (timer);
	g_print ("regex search: 10 matches of %d lines (big partial matches): %lf seconds.\n",
		 NB_LINES / 10,
		 g_timer_elapsed (timer, NULL));

	/* Smart search, case sensitive, asynchronous */

	/* The asynchronous overhead doesn't depend on the search flags, it
	 * depends on the maximum number of lines to scan in one batch, and
	 * (obviously), on the buffer size.
	 * You can tune SCAN_BATCH_SIZE in gtksourcesearchcontext.c to see a
	 * difference in the overhead.
	 */

	g_signal_connect (search_context,
			  "notify::occurrences-count",
			  G_CALLBACK (on_notify_search_occurrences_count_cb),
			  timer);

	g_timer_start (timer);

	gtk_source_search_settings_set_search_text (search_settings, NULL);
	gtk_source_search_settings_set_regex_enabled (search_settings, FALSE);
	gtk_source_search_settings_set_search_text (search_settings, "foo");

	gtk_main ();
	return 0;
}
int main (int argc, char **argv)
{
#ifdef VSG_HAVE_MPI
  VsgPRTreeParallelConfig pconfig = {{NULL,}};
#endif

  VsgVector3d lbound = {-TR, -TR, -TR};
  VsgVector3d ubound = {TR, TR, TR};
  VsgPRTree3d *prtree;
  AranSolver3d *solver;
  int ret = 0;
  GTimer *timer = NULL;

#ifdef VSG_HAVE_MPI
  MPI_Init (&argc, &argv);

  MPI_Comm_size (MPI_COMM_WORLD, &sz);
  MPI_Comm_rank (MPI_COMM_WORLD, &rk);
#endif

  aran_init();

  parse_args (argc, argv);

#ifdef VSG_HAVE_MPI
  pconfig.communicator = MPI_COMM_WORLD;

  pconfig.point = point_accum_vtable;

  aran_development3d_vtable_init (&pconfig.node_data, 0, order);
#endif

  points = g_ptr_array_new ();

  if (check)
    {
      _cp_size = MAX (np, 128);
      check_points = g_malloc0 (_cp_size * sizeof (PointAccum));
    }

  prtree =
    vsg_prtree3d_new_full (&lbound, &ubound,
                            (VsgPoint3dLocFunc) vsg_vector3d_vector3d_locfunc,
                            (VsgPoint3dDistFunc) vsg_vector3d_dist,
                            (VsgRegion3dLocFunc) NULL, maxbox);

  solver = aran_solver3d_new (prtree, ARAN_TYPE_DEVELOPMENT3D,
                              aran_development3d_new (0, order),
                              (AranZeroFunc) aran_development3d_set_zero);

#ifdef VSG_HAVE_MPI
  aran_solver3d_set_parallel (solver, &pconfig);
#endif

  aran_solver3d_set_functions (solver,
                               (AranParticle2ParticleFunc3d) p2p,
                               (AranParticle2MultipoleFunc3d) p2m,
                               m2m,
                               m2l,
                               l2l,
                               (AranLocal2ParticleFunc3d) l2p);

  if (_hilbert)
    {
      /* configure for hilbert curve order traversal */
      aran_solver3d_set_children_order_hilbert (solver);
    }

  _fill (solver);

/*   g_printerr ("ok depth = %d size = %d\n", */
/*               aran_solver3d_depth (solver), */
/*               aran_solver3d_point_count (solver)); */

  if (_verbose)
    {
      g_printerr ("%d : solve begin\n", rk);

#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      timer = g_timer_new ();
    }

  aran_solver3d_solve (solver);

  if (_verbose)
    {
#ifdef VSG_HAVE_MPI
      MPI_Barrier (MPI_COMM_WORLD);
#endif

      g_printerr ("%d : solve ok elapsed=%f seconds\n", rk,
                  g_timer_elapsed (timer, NULL));

      g_timer_destroy (timer);
    }

  if (_write)
    {
      gchar fn[1024];
      FILE *f;

      g_sprintf (fn, "tree%03d.txt", rk);
      f = fopen (fn, "w");
      vsg_prtree3d_write (prtree, f);
      fclose (f);

      _tree_write (prtree, "solv");
      _vtp_tree_write (solver, "solv");
    }

  if (check)
    {
      gint i, j;

      if (sz == 1)
        {
          for (i=0; i<np; i ++)
            {
              PointAccum *pi = &check_points[i];

              for (j=0; j<np; j ++)
                {
                  if (j != i)
                    {
                      PointAccum *pj = &check_points[j];
                      p2p_one_way (pi, pj);
                    }
                }

            }
        }
      else
        check_parallel_points (solver);

      aran_solver3d_foreach_point (solver, (GFunc) check_point_field, &ret);

      if (_verbose)
        g_printerr ("%d : max err = %e\n", rk, maxerr);

      g_free (check_points);
    }

  aran_solver3d_free (solver);

#ifdef VSG_HAVE_MPI
  aran_development3d_vtable_clear (&pconfig.node_data);
#endif

  g_ptr_array_free (points, TRUE);

  if (_load_file != NULL) g_free (_load_file);

#ifdef VSG_HAVE_MPI
  MPI_Finalize ();
#endif

  return ret;
}
示例#19
0
static gboolean
run_parsing (void)
{
    TrackerFTSConfig *config;
    TrackerLanguage *language;
    TrackerParser *parser;
    GTimer *timer;

    /* Initialize timing */
    timer = g_timer_new ();

    /* Read config file */
    config = tracker_fts_config_new ();

    /* Setup language for parser */
    language = tracker_language_new (NULL);
    if (!language) {
        g_printerr ("Language setup failed!\n");
        return FALSE;
    }

    /* Create the parser */
    parser = tracker_parser_new (language);
    if (!parser) {
        g_printerr ("Parser creation failed!\n");
        g_object_unref (language);
        return FALSE;
    }

    /* Reset the parser with our string, reading the current FTS config */
    tracker_parser_reset (parser,
                          text,
                          strlen (text),
                          tracker_fts_config_get_max_word_length (config),
                          tracker_fts_config_get_enable_stemmer (config),
                          tracker_fts_config_get_enable_unaccent (config),
                          tracker_fts_config_get_ignore_stop_words (config),
                          TRUE,
                          tracker_fts_config_get_ignore_numbers (config));

    /* Loop through all words! */
    while (1) {
        const gchar *word;
        gint position;
        gint byte_offset_start;
        gint byte_offset_end;
        gboolean stop_word;
        gint word_length;


        /* Process next word */
        word = tracker_parser_next (parser,
                                    &position,
                                    &byte_offset_start,
                                    &byte_offset_end,
                                    &stop_word,
                                    &word_length);

        /* Stop loop if no more words */
        if (!word) {
            break;
        }

        if (verbose) {
            gchar *word_hex;
            gchar *original_word;
            gchar *original_word_hex;
            gint original_word_length;

            /* Get original word */
            original_word_length = byte_offset_end - byte_offset_start;
            original_word = g_malloc (original_word_length + 1);
            memcpy (original_word,
                    &text[byte_offset_start],
                    original_word_length);
            original_word[original_word_length] = '\0';

            /* Get hex strings */
            word_hex = tracker_strhex (word, word_length, ':');
            original_word_hex = tracker_strhex (original_word,
                                                original_word_length,
                                                ':');

            g_print ("WORD at %d [%d,%d] Original: '%s' (%s), "
                     "Processed: '%s' (%s) (stop? %s)\n",
                     position,
                     byte_offset_start,
                     byte_offset_end,
                     original_word,
                     original_word_hex,
                     word,
                     word_hex,
                     stop_word ? "yes" : "no");

            g_free (word_hex);
            g_free (original_word_hex);
            g_free (original_word);
        }
    }

    g_print ("\n----> Parsing finished after '%lf' seconds\n",
             g_timer_elapsed (timer, NULL));

    g_timer_destroy (timer);

    tracker_parser_free (parser);
    g_object_unref (language);
    return TRUE;
}
示例#20
0
static void
test_many_tasks_many_immediates(TestFixture *fixture,
                                const void  *data)
{
    int i, j;
    gboolean some_overlap;
    GTimer *timer;
    GString *overlap_report;

    /* this has to be set up front of there's a race in using it to
     * decide to quit mainloop, because task runner starts running
     * tasks right away, doesn't wait for our local mainloop
     */
    fixture->tasks_started_count = NUM_TASKS;

    for (i = 0; i < NUM_TASKS; ++i) {
        HrtTask *task;

        task = hrt_task_runner_create_task(fixture->runner);
        fixture->tasks[i].task = task;

        /* note that we serialize all immediates for a task so making this
         * a large number will take forever
         */
#define NUM_IMMEDIATES 7
        for (j = 0; j < NUM_IMMEDIATES; ++j) {
            hrt_task_add_immediate(task,
                                   on_immediate_for_many_tasks,
                                   fixture,
                                   on_dnotify_bump_count);
        }
    }

    timer = g_timer_new();

    g_main_loop_run(fixture->loop);

    /* we don't want an assertion based on timing, will fail too often,
     * but print it for manual checking sometimes.
     */
    g_test_message("%g seconds elapsed to run lots of tasks that should have each taken 0.7 seconds\n",
                   g_timer_elapsed(timer, NULL));
    g_timer_destroy(timer);

    g_assert_cmpint(fixture->tasks_completed_count, ==, NUM_TASKS);
    g_assert_cmpint(fixture->tasks_completed_count, ==,
                    fixture->tasks_started_count);
    g_assert_cmpint(fixture->dnotify_count, ==, NUM_IMMEDIATES * NUM_TASKS);
    /* we should have run each immediate exactly once */
    for (i = 0; i < NUM_TASKS; ++i) {
        g_assert(fixture->tasks[i].immediates_run_count == NUM_IMMEDIATES);
    }

    /* unfortunately this isn't strictly guaranteed, but it should be
     * nearly certain. If it keeps failing, increase number of immediates
     * and number of tasks.
     */
    some_overlap = FALSE;
    for (i = 0; i < NUM_TASKS; ++i) {
        if (fixture->tasks[i].saw_another_immediate_in_an_immediate_count > 0)
            some_overlap = TRUE;
    }
    g_assert(some_overlap);

    overlap_report = g_string_new(NULL);
    for (i = 0; i < NUM_TASKS; ++i) {
        g_string_append_printf(overlap_report,
                               " %d",
                               fixture->tasks[i].saw_another_immediate_in_an_immediate_count);
    }
    g_test_message("# of immediates of %d run during at least one other task's immediate:\n  %s\n",
                   NUM_IMMEDIATES,
                   overlap_report->str);
    g_string_free(overlap_report, TRUE);
#undef NUM_IMMEDIATES
}
示例#21
0
文件: gui.c 项目: vincentdoba/LPlayer
int main(int argc, char **argv) {

    struct arguments argument;
    struct arguments *pargument = &argument;

    //InitOpenAL(); // potential memory leak
    source = 0;
    pargument->first = 1;
    pargument->endless_check = 0;
    pargument->continue_count = 0;
    pargument->offset = 0;
    pargument->elapsed = g_timer_new();
    GtkWidget *window, *hpaned, *pause_button, *bitrate_label, *chooser1, *chooser2, *chooser3, *vboxl, *vboxr, *check,
              *continue_check, *continue_label, *next_button, *button2, *spin_int, *progressbar, *button_hbox, *continue_hbox;
    GtkFileFilter *filter1, *filter2;

    gtk_init(&argc, &argv);

    //g_remove("list.txt");
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

    pargument->adjust = (GtkAdjustment*)gtk_adjustment_new(0, 0, 100, 1, 1, 1);

#if GTK3
    progressbar = gtk_scale_new(GTK_ORIENTATION_HORIZONTAL, adjust);
#endif
    progressbar = gtk_hscale_new(pargument->adjust);
    gtk_scale_set_draw_value ((GtkScale*)progressbar, FALSE);
    gtk_window_set_title(GTK_WINDOW(window), "lelele player");
    pargument->label = gtk_label_new ("");
    pargument->title_label = gtk_label_new("");
    pargument->album_label = gtk_label_new("");
    pargument->artist_label = gtk_label_new("");
    gtk_label_set_line_wrap((GtkLabel*)pargument->title_label, TRUE);
    gtk_label_set_line_wrap((GtkLabel*)pargument->artist_label, TRUE);
    gtk_label_set_line_wrap((GtkLabel*)pargument->album_label, TRUE);
    continue_label = gtk_label_new("Number of songs played\n -1 to go endless");

    gtk_container_set_border_width(GTK_CONTAINER(window), 10);
    gtk_widget_set_size_request(window, 500, 250);
    hpaned = gtk_hpaned_new();

    spin_int = gtk_spin_button_new_with_range(-1, 10000, 1);
    gtk_spin_button_set_value ((GtkSpinButton*)spin_int, 1);
    pause_button = gtk_button_new_with_mnemonic("_Play/Pause");
    next_button = gtk_button_new_with_mnemonic("Next");
    check = gtk_check_button_new_with_label ("Endless mode.");
    //continue_check = gtk_check_button_new_with_label("Play this number of songs.");


    g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (destroy), NULL);
    g_signal_connect (G_OBJECT(pause_button), "clicked", G_CALLBACK(play), pargument);
    g_signal_connect (G_OBJECT(next_button), "clicked", G_CALLBACK(next), pargument);
    g_signal_connect (G_OBJECT(check), "toggled", G_CALLBACK(check_toggled), pargument);
    //g_signal_connect(G_OBJECT(continue_check), "toggled", G_CALLBACK(continue_check_toggled), spin_int);
    g_signal_connect(G_OBJECT(spin_int), "value-changed", G_CALLBACK(continue_spin_count), pargument);
    g_signal_connect(G_OBJECT(progressbar), "value-changed", G_CALLBACK(slider_changed), pargument);


    /* Create two buttons, one to select a folder and one to select a file. */

    chooser1 = gtk_file_chooser_button_new ("Chooser a Folder", GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);
    chooser2 = gtk_file_chooser_button_new ("Chooser a Folder", GTK_FILE_CHOOSER_ACTION_OPEN);
    chooser3 = gtk_file_chooser_button_new ("Choose a folder for config (may take some time)", GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER);

    /* Monitor when the selected folder or file are changed. */
    g_signal_connect (G_OBJECT (chooser2), "selection_changed", G_CALLBACK (file_changed), pargument);
    g_signal_connect (G_OBJECT (chooser1), "selection_changed", G_CALLBACK(folder_changed), pargument);
    g_signal_connect (G_OBJECT (chooser3), "selection_changed", G_CALLBACK (config_folder_changed), pargument);

    /* Set both file chooser buttons to the location of the user's home directory. */
    gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (chooser2), g_get_home_dir());

    gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (chooser1), g_get_home_dir());
    /* Provide a filter to show all files and one to shown only 3 types of images. */
    filter1 = gtk_file_filter_new ();
    filter2 = gtk_file_filter_new ();
    gtk_file_filter_set_name (filter1, "Audio Files");
    gtk_file_filter_set_name (filter2, "All Files");
    gtk_file_filter_add_pattern (filter1, "*.mp3");
    gtk_file_filter_add_pattern (filter1, "*.flac");
    gtk_file_filter_add_pattern (filter1, "*.aac");
    gtk_file_filter_add_pattern (filter2, "*");

    /* Add the both filters to the file chooser button that selects files. */
    gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser2), filter1);
    gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (chooser2), filter2);


    //gtk_widget_set_sensitive(spin_int, FALSE);
    vboxl = gtk_vbox_new (TRUE, 5);
    vboxr = gtk_vbox_new (TRUE, 5);
    button_hbox = gtk_hbox_new (TRUE, 5);
    continue_hbox= gtk_hbox_new (TRUE, 5);

    gtk_box_set_homogeneous(GTK_BOX(vboxr), FALSE);
    gtk_box_set_homogeneous(GTK_BOX(continue_hbox), FALSE);

    gtk_box_pack_start_defaults (GTK_BOX (vboxl), chooser1);
    gtk_box_pack_start_defaults (GTK_BOX (vboxl), chooser2);
//	gtk_box_pack_start_defaults (GTK_BOX (vboxl), chooser3);
    //gtk_box_pack_start_defaults (GTK_BOX (vboxl), check);

    gtk_box_pack_start_defaults (GTK_BOX (vboxl), continue_hbox);
    gtk_box_pack_start_defaults (GTK_BOX(continue_hbox), continue_label);
    gtk_box_pack_start_defaults (GTK_BOX(continue_hbox), spin_int);
    gtk_box_pack_start_defaults (GTK_BOX (vboxl), button_hbox);
    gtk_box_pack_start_defaults (GTK_BOX (button_hbox), pause_button);
    gtk_box_pack_start_defaults (GTK_BOX(button_hbox), next_button);
    gtk_box_pack_start_defaults (GTK_BOX(vboxl), progressbar);

    gtk_box_pack_start(GTK_BOX (vboxr), pargument->label, FALSE, FALSE, 1);
    gtk_box_pack_start(GTK_BOX (vboxr), pargument->title_label, FALSE, FALSE, 1);
    gtk_box_pack_start(GTK_BOX (vboxr), pargument->album_label, FALSE, FALSE, 1);
    gtk_box_pack_start(GTK_BOX (vboxr), pargument->artist_label, FALSE, FALSE, 1);

#ifdef GTK3
    vboxl = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
    vboxr = gtk_vboxr_new (GTK_ORIENTATION_VERTICAL, 5);
    gtk_box_pack_start (GTK_BOX (vboxl), chooser1, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX (vboxl), chooser2, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX (vboxl), pause_button, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX(vboxl), next_button, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX (vboxl), pargument->label, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX (vboxl), check, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX(vboxl), continue_check, TRUE, TRUE, 3);
    gtk_box_pack_start (GTK_BOX(vboxl), spin_int, TRUE, TRUE, 3);

    gtk_box_pack_start (GTK_BOX(vboxl), progressbar, TRUE, TRUE, 3);

    gtk_box_pack_start (GTK_BOX (vboxr), pargument->label, TRUE, TRUE, 3);
    gtk_box_pack_start_defaults (GTK_BOX (vboxr), pargument->title_label, TRUE, TRUE, 3);
    gtk_box_pack_start_defaults (GTK_BOX (vboxr), pargument->album_label, TRUE, TRUE, 3);
    gtk_box_pack_start_defaults (GTK_BOX (vboxr), pargument->artist_label, TRUE, TRUE, 3);

#endif

    gtk_paned_pack1(GTK_PANED(hpaned), vboxl, FALSE, FALSE);
    gtk_paned_pack2(GTK_PANED(hpaned), vboxr, TRUE, FALSE);
    gtk_container_add (GTK_CONTAINER (window), hpaned);

    gtk_widget_show_all(window);

    gtk_main();
    return 0;
}
示例#22
0
static gboolean get_power_supply (gchar *battery_suffix, gboolean list_power_supply)
{
    GDir *directory;
    GError *error = NULL;
    const gchar *file;
    gchar *path;
    gchar *sysattr_value;
    gboolean sysattr_status;

    directory = g_dir_open (SYSFS_PATH, 0, &error);
    if (directory != NULL) {
        file = g_dir_read_name (directory);
        while (file != NULL) {
            path = g_build_filename (SYSFS_PATH, file, NULL);

            sysattr_status = get_sysattr_string (path, "type", &sysattr_value);
            if (sysattr_status == TRUE) {
                /* process battery */
                if (g_str_has_prefix (sysattr_value, "Battery") == TRUE) {
                    if (list_power_supply == TRUE) {
                        gchar *power_supply_id = g_path_get_basename (path);
                        g_print (_("type: %-*.*s\tid: %-*.*s\tpath: %s\n"), 12, 12, _("Battery"), 12, 12, power_supply_id, path);
                        g_free (power_supply_id);
                    }

                    if (battery_path == NULL) {
                        if (battery_suffix == NULL ||
                            g_str_has_suffix (path, battery_suffix) == TRUE) {
                            battery_path = g_strdup (path);

                            /* workaround for limited/bugged batteries/drivers */
                            /* that don't provide current rate                 */
                            if (get_battery_current_rate (FALSE, NULL) == FALSE &&
                                get_battery_current_rate (TRUE, NULL) == FALSE) {
                                estimation_needed = TRUE;
                                estimation_timer = g_timer_new ();

                                if (configuration.debug_output == TRUE) {
                                    g_printf (_("workaround: current rate is not available, estimating rate\n"));
                                }
                            }

                            if (configuration.debug_output == TRUE) {
                                g_printf (_("battery path: %s\n"), battery_path);
                            }
                        }
                    }
                }

                /* process AC */
                if (g_str_has_prefix (sysattr_value, "Mains") == TRUE) {
                    if (list_power_supply == TRUE) {
                        gchar *power_supply_id = g_path_get_basename (path);
                        g_print (_("type: %-*.*s\tid: %-*.*s\tpath: %s\n"), 12, 12, _("AC"), 12, 12, power_supply_id, path);
                        g_free (power_supply_id);
                    }

                    if (ac_path == NULL) {
                        ac_path = g_strdup (path);

                        if (configuration.debug_output == TRUE) {
                            g_printf (_("ac path: %s\n"), ac_path);
                        }
                    }
                }

                g_free (sysattr_value);
            }

            g_free (path);
            file = g_dir_read_name (directory);
        }

        g_dir_close (directory);
    } else {
        g_printerr (_("Cannot open sysfs directory: %s (%s)\n"), SYSFS_PATH, error->message);
        g_error_free (error); error = NULL;
        return FALSE;
    }

    if (list_power_supply == FALSE && battery_path == NULL) {
        if (battery_suffix != NULL) {
            g_printerr (_("No battery with suffix %s found!\n"), battery_suffix);
            return FALSE;
        }

        if (ac_path == NULL) {
            g_printerr (_("No battery nor AC power supply found!\n"));
            return FALSE;
        }
    }

    return TRUE;
}
static void
run_theme_benchmark (void)
{
    GtkWidget* widget;
    GdkPixmap *pixmap;
    int top_height, bottom_height, left_width, right_width;
    MetaButtonState button_states[META_BUTTON_TYPE_LAST] =
    {
        META_BUTTON_STATE_NORMAL,
        META_BUTTON_STATE_NORMAL,
        META_BUTTON_STATE_NORMAL,
        META_BUTTON_STATE_NORMAL
    };
    PangoLayout *layout;
    clock_t start;
    clock_t end;
    GTimer *timer;
    int i;
    MetaButtonLayout button_layout;
#define ITERATIONS 100
    int client_width;
    int client_height;
    int inc;

    widget = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_widget_realize (widget);

    meta_theme_get_frame_borders (global_theme,
                                  META_FRAME_TYPE_NORMAL,
                                  get_text_height (widget),
                                  get_flags (widget),
                                  &top_height,
                                  &bottom_height,
                                  &left_width,
                                  &right_width);

    layout = create_title_layout (widget);

    i = 0;
    while (i < MAX_BUTTONS_PER_CORNER)
    {
        button_layout.left_buttons[i] = META_BUTTON_FUNCTION_LAST;
        button_layout.right_buttons[i] = META_BUTTON_FUNCTION_LAST;
        ++i;
    }

    button_layout.left_buttons[0] = META_BUTTON_FUNCTION_MENU;

    button_layout.right_buttons[0] = META_BUTTON_FUNCTION_MINIMIZE;
    button_layout.right_buttons[1] = META_BUTTON_FUNCTION_MAXIMIZE;
    button_layout.right_buttons[2] = META_BUTTON_FUNCTION_CLOSE;

    timer = g_timer_new ();
    start = clock ();

    client_width = 50;
    client_height = 50;
    inc = 1000 / ITERATIONS; /* Increment to grow width/height,
                            * eliminates caching effects.
                            */

    i = 0;
    while (i < ITERATIONS)
    {
        /* Creating the pixmap in the loop is right, since
         * GDK does the same with its double buffering.
         */
        pixmap = gdk_pixmap_new (gtk_widget_get_window (widget),
                                 client_width + left_width + right_width,
                                 client_height + top_height + bottom_height,
                                 -1);

        meta_theme_draw_frame (global_theme,
                               widget,
                               pixmap,
                               NULL,
                               0, 0,
                               META_FRAME_TYPE_NORMAL,
                               get_flags (widget),
                               client_width, client_height,
                               layout,
                               get_text_height (widget),
                               &button_layout,
                               button_states,
                               meta_preview_get_mini_icon (),
                               meta_preview_get_icon ());

        g_object_unref (G_OBJECT (pixmap));

        ++i;
        client_width += inc;
        client_height += inc;
    }

    end = clock ();
    g_timer_stop (timer);

    milliseconds_to_draw_frame = (g_timer_elapsed (timer, NULL) / (double) ITERATIONS) * 1000;

    g_print (_("Drew %d frames in %g client-side seconds (%g milliseconds per frame) and %g seconds wall clock time including X server resources (%g milliseconds per frame)\n"),
             ITERATIONS,
             ((double)end - (double)start) / CLOCKS_PER_SEC,
             (((double)end - (double)start) / CLOCKS_PER_SEC / (double) ITERATIONS) * 1000,
             g_timer_elapsed (timer, NULL),
             milliseconds_to_draw_frame);

    g_timer_destroy (timer);
    g_object_unref (G_OBJECT (layout));
    gtk_widget_destroy (widget);

#undef ITERATIONS
}
示例#24
0
文件: mgobj.c 项目: LordJagged/mosh
MOSHEXPORT
void*
mglib_timer_new(void){
    return g_timer_new();
}
示例#25
0
gboolean
lr_fastestmirror_sort_internalmirrorlists(GSList *handles,
                                          GError **err)
{
    assert(!err || *err == NULL);

    if (!handles)
        return TRUE;

    GTimer *timer = g_timer_new();
    g_timer_start(timer);

    LrHandle *main_handle = handles->data;  // Network configuration for the
                                            // test is used from the first
                                            // handle

    // Prepare list of hosts
    gchar *fastestmirrorcache = main_handle->fastestmirrorcache;
    GHashTable *hosts_ht = g_hash_table_new_full(g_str_hash,
                                                 g_str_equal,
                                                 g_free,
                                                 NULL);

    for (GSList *ehandle = handles; ehandle; ehandle = g_slist_next(ehandle)) {
        LrHandle *handle = ehandle->data;
        GSList *mirrors = handle->internal_mirrorlist;
        for (GSList *elem = mirrors; elem; elem = g_slist_next(elem)) {
            LrInternalMirror *imirror = elem->data;
            gchar *host = lr_url_without_path(imirror->url);
            g_hash_table_insert(hosts_ht, host, NULL);
        }

        // Cache related warning
        if (fastestmirrorcache) {
            if (handle->fastestmirrorcache
                && g_strcmp0(fastestmirrorcache, handle->fastestmirrorcache))
                g_warning("%s: Multiple fastestmirror caches are specified! "
                          "Used one is %s (%s is ignored)", __func__,
                          fastestmirrorcache, handle->fastestmirrorcache);
        } else {
            if (handle->fastestmirrorcache)
                g_warning("%s: First handle doesn't have a fastestmirror "
                          "cache specified but other one has: %s",
                          __func__, handle->fastestmirrorcache);
        }
    }

    GList *tmp_list_of_urls = g_hash_table_get_keys(hosts_ht);
    GSList *list_of_urls = NULL;
    int number_of_mirrors = 0;
    for (GList *elem = tmp_list_of_urls; elem; elem = g_list_next(elem)) {
        list_of_urls = g_slist_prepend(list_of_urls, elem->data);
        number_of_mirrors++;
    }
    g_list_free(tmp_list_of_urls);

    if (number_of_mirrors <= 1) {
        // Nothing to do
        g_slist_free(list_of_urls);
        g_hash_table_destroy(hosts_ht);
        g_timer_destroy(timer);
        return TRUE;
    }

    // Sort this list by the connection time
    gboolean ret = lr_fastestmirror(main_handle,
                                    &list_of_urls,
                                    err);
    if (!ret) {
        g_debug("%s: lr_fastestmirror failed", __func__);
        g_slist_free(list_of_urls);
        g_hash_table_destroy(hosts_ht);
        g_timer_destroy(timer);
        return FALSE;
    }

    // Apply sorted order to each handle
    for (GSList *ehandle = handles; ehandle; ehandle = g_slist_next(ehandle)) {
        LrHandle *handle = ehandle->data;
        GSList *mirrors = handle->internal_mirrorlist;
        GSList *new_list = NULL;
        for (GSList *elem = list_of_urls; elem; elem = g_slist_next(elem)) {
            gchar *host = elem->data;
            for (GSList *ime = mirrors; ime; ime = g_slist_next(ime)) {
                LrInternalMirror *im = ime->data;
                gchar *im_host = lr_url_without_path(im->url);
                if (!g_strcmp0(im_host, host)) {
                    new_list = g_slist_prepend(new_list, im);
                    // XXX: Maybe convert GSList to GList to make
                    // this delete more efficient
                    mirrors = g_slist_delete_link(mirrors, ime);
                    break;
                }
            }
        }

        // If multiple mirrors with the same lr_url_without_path(url)
        // were present, only the first occurrence was inserted to the
        // the new_list and removed from the mirrors list.
        // The remaining occurences will be moved here.
        for (GSList *elem = mirrors; elem; elem = g_slist_next(elem)) {
            LrInternalMirror *im = elem->data;
            new_list = g_slist_prepend(new_list, im);
        }
        g_slist_free(mirrors);

        // Set sorted list to the handle (reversed, because the items
        // of the new_list were prepended)
        handle->internal_mirrorlist = g_slist_reverse(new_list);
    }

    g_slist_free(list_of_urls);
    g_hash_table_destroy(hosts_ht);

    g_timer_stop(timer);
    g_debug("%s: Duration: %f", __func__, g_timer_elapsed(timer, NULL));
    g_timer_destroy(timer);

    return TRUE;
}
示例#26
0
static gpointer
holding_thread(
    gpointer data)
{
    XferDestHolding *self = XFER_DEST_HOLDING(data);
    XferElement *elt = XFER_ELEMENT(self);
    XMsg *msg;
    gchar *mesg = NULL;
    GTimer *timer = g_timer_new();

    DBG(1, "(this is the holding thread)");

    /* This is the outer loop, that loops once for each holding file or
     * CONTINUE command */
    g_mutex_lock(self->state_mutex);
    while (1) {
	gboolean done;
	/* wait until the main thread un-pauses us, and check that we have
	 * the relevant holding info available */
	while (self->paused && !elt->cancelled) {
	    DBG(9, "waiting to be unpaused");
	    g_cond_wait(self->state_cond, self->state_mutex);
	}
	DBG(9, "holding_thread done waiting");

        if (elt->cancelled)
	    break;

	self->data_bytes_written = 0;
	self->header_bytes_written = 0;

	/* new holding file */
	if (self->filename == NULL ||
	    strcmp(self->filename, self->new_filename) != 0) {
	    char    *tmp_filename;
	    char    *pc;
	    int      fd;
	    ssize_t  write_header_size;

	    if (self->use_bytes < HEADER_BLOCK_BYTES) {
		self->chunk_status = CHUNK_NO_ROOM;
		goto no_room;
	    }

	    tmp_filename = g_strjoin(NULL, self->new_filename, ".tmp", NULL);
	    pc = strrchr(tmp_filename, '/');
	    g_assert(pc != NULL);
	    *pc = '\0';
	    mkholdingdir(tmp_filename);
	    *pc = '/';

	    fd = open(tmp_filename, O_RDWR|O_CREAT|O_TRUNC, 0600);
	    if (fd < 0) {
		self->chunk_status = CHUNK_NO_ROOM;
		g_free(mesg);
		mesg = g_strdup_printf("Failed to open '%s': %s",
				       tmp_filename, strerror(errno));
		g_free(tmp_filename);
		goto no_room;
	    }
	    if (self->filename == NULL) {
		self->chunk_header->type = F_DUMPFILE;
	    } else {
		self->chunk_header->type = F_CONT_DUMPFILE;
	    }
	    self->chunk_header->cont_filename[0] = '\0';

	    write_header_size = write_header(self, fd);
	    if (write_header_size != HEADER_BLOCK_BYTES) {
		self->chunk_status = CHUNK_NO_ROOM;
		mesg = g_strdup_printf("Failed to write header to '%s': %s",
				       tmp_filename, strerror(errno));
		close(fd);
		unlink(tmp_filename);
		g_free(tmp_filename);
		goto no_room;
	    }
	    g_free(tmp_filename);
	    self->use_bytes -= HEADER_BLOCK_BYTES;

	    /* rewrite old_header */
	    if (self->filename &&
		strcmp(self->filename, self->new_filename) != 0) {
		close_chunk(self, self->new_filename);
	    }
	    self->filename = self->new_filename;
	    self->new_filename = NULL;
	    self->fd = fd;
	    self->header_bytes_written = HEADER_BLOCK_BYTES;
	    self->chunk_offset = HEADER_BLOCK_BYTES;
	}

	DBG(2, "beginning to write chunk");
	done = holding_thread_write_chunk(self);
	DBG(2, "done writing chunk");

	if (!done) /* cancelled */
	    break;

no_room:
	msg = xmsg_new(XFER_ELEMENT(self), XMSG_CHUNK_DONE, 0);
	msg->header_size = self->header_bytes_written;
	msg->data_size = self->data_bytes_written;
	msg->no_room = (self->chunk_status == CHUNK_NO_ROOM);
	if (mesg) {
	    msg->message = mesg;
	    mesg = NULL;
	}

	xfer_queue_message(elt->xfer, msg);

	/* pause ourselves and await instructions from the main thread */
	self->paused = TRUE;

	/* if this is the last part, we're done with the chunk loop */
	if (self->chunk_status == CHUNK_EOF) {
	    break;
	}
    }
    g_mutex_unlock(self->state_mutex);

    g_debug("sending XMSG_CRC message");
    g_debug("xfer-dest-holding CRC: %08x     size: %lld",
	    crc32_finish(&elt->crc), (long long)elt->crc.size);
    msg = xmsg_new(XFER_ELEMENT(self), XMSG_CRC, 0);
    msg->crc = crc32_finish(&elt->crc);
    msg->size = elt->crc.size;
    xfer_queue_message(elt->xfer, msg);

    msg = xmsg_new(XFER_ELEMENT(self), XMSG_DONE, 0);
    msg->duration = g_timer_elapsed(timer, NULL);
    g_timer_destroy(timer);
    /* tell the main thread we're done */
    xfer_queue_message(elt->xfer, msg);

    return NULL;
}
示例#27
0
int
main (int   argc,
      char *argv[])
{
  GList *list, *t;
  GSList *slist, *st;
  GHashTable *hash_table;
  GMemChunk *mem_chunk;
  GStringChunk *string_chunk;
  GTimer *timer;
  gint nums[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  gint morenums[10] = { 8, 9, 7, 0, 3, 2, 5, 1, 4, 6};
  gchar *string;

  gchar *mem[10000], *tmp_string = NULL, *tmp_string_2;
  gint i, j;
  GArray *garray;
  GPtrArray *gparray;
  GByteArray *gbarray;
  GString *string1, *string2;
  GTree *tree;
  char chars[62];
  GRelation *relation;
  GTuples *tuples;
  gint data [1024];
  struct {
    gchar *filename;
    gchar *dirname;
  } dirname_checks[] = {
#ifndef NATIVE_WIN32
    { "/", "/" },
    { "////", "/" },
    { ".////", "." },
    { ".", "." },
    { "..", "." },
    { "../", ".." },
    { "..////", ".." },
    { "", "." },
    { "a/b", "a" },
    { "a/b/", "a/b" },
    { "c///", "c" },
#else
    { "\\", "\\" },
    { ".\\\\\\\\", "." },
    { ".", "." },
    { "..", "." },
    { "..\\", ".." },
    { "..\\\\\\\\", ".." },
    { "", "." },
    { "a\\b", "a" },
    { "a\\b\\", "a\\b" },
    { "c\\\\\\", "c" },
#endif
  };
  guint n_dirname_checks = sizeof (dirname_checks) / sizeof (dirname_checks[0]);
  guint16 gu16t1 = 0x44afU, gu16t2 = 0xaf44U;
  guint32 gu32t1 = 0x02a7f109U, gu32t2 = 0x09f1a702U;
#ifdef G_HAVE_GINT64
  guint64 gu64t1 = G_GINT64_CONSTANT(0x1d636b02300a7aa7U),
	  gu64t2 = G_GINT64_CONSTANT(0xa77a0a30026b631dU);
#endif

  g_print ("TestGLib v%u.%u.%u (i:%u b:%u)\n",
	   glib_major_version,
	   glib_minor_version,
	   glib_micro_version,
	   glib_interface_age,
	   glib_binary_age);

  string = g_get_current_dir ();
  g_print ("cwd: %s\n", string);
  g_free (string);
  g_print ("user: %s\n", g_get_user_name ());
  g_print ("real: %s\n", g_get_real_name ());
  g_print ("home: %s\n", g_get_home_dir ());
  g_print ("tmp-dir: %s\n", g_get_tmp_dir ());

  /* type sizes */
  g_print ("checking size of gint8: %d", (int)sizeof (gint8));
  TEST (NULL, sizeof (gint8) == 1);
  g_print ("\nchecking size of gint16: %d", (int)sizeof (gint16));
  TEST (NULL, sizeof (gint16) == 2);
  g_print ("\nchecking size of gint32: %d", (int)sizeof (gint32));
  TEST (NULL, sizeof (gint32) == 4);
#ifdef	G_HAVE_GINT64
  g_print ("\nchecking size of gint64: %d", (int)sizeof (gint64));
  TEST (NULL, sizeof (gint64) == 8);
#endif	/* G_HAVE_GINT64 */
  g_print ("\n");

  g_print ("checking g_dirname()...");
  for (i = 0; i < n_dirname_checks; i++)
    {
      gchar *dirname;

      dirname = g_dirname (dirname_checks[i].filename);
      if (strcmp (dirname, dirname_checks[i].dirname) != 0)
	{
	  g_print ("\nfailed for \"%s\"==\"%s\" (returned: \"%s\")\n",
		   dirname_checks[i].filename,
		   dirname_checks[i].dirname,
		   dirname);
	  n_dirname_checks = 0;
	}
      g_free (dirname);
    }
  if (n_dirname_checks)
    g_print ("ok\n");

  g_print ("checking doubly linked lists...");

  list = NULL;
  for (i = 0; i < 10; i++)
    list = g_list_append (list, &nums[i]);
  list = g_list_reverse (list);

  for (i = 0; i < 10; i++)
    {
      t = g_list_nth (list, i);
      if (*((gint*) t->data) != (9 - i))
	g_error ("Regular insert failed");
    }

  for (i = 0; i < 10; i++)
    if(g_list_position(list, g_list_nth (list, i)) != i)
      g_error("g_list_position does not seem to be the inverse of g_list_nth\n");

  g_list_free (list);
  list = NULL;

  for (i = 0; i < 10; i++)
    list = g_list_insert_sorted (list, &morenums[i], my_list_compare_one);

  /*
  g_print("\n");
  g_list_foreach (list, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      t = g_list_nth (list, i);
      if (*((gint*) t->data) != i)
         g_error ("Sorted insert failed");
    }

  g_list_free (list);
  list = NULL;

  for (i = 0; i < 10; i++)
    list = g_list_insert_sorted (list, &morenums[i], my_list_compare_two);

  /*
  g_print("\n");
  g_list_foreach (list, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      t = g_list_nth (list, i);
      if (*((gint*) t->data) != (9 - i))
         g_error ("Sorted insert failed");
    }

  g_list_free (list);
  list = NULL;

  for (i = 0; i < 10; i++)
    list = g_list_prepend (list, &morenums[i]);

  list = g_list_sort (list, my_list_compare_two);

  /*
  g_print("\n");
  g_list_foreach (list, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      t = g_list_nth (list, i);
      if (*((gint*) t->data) != (9 - i))
         g_error ("Merge sort failed");
    }

  g_list_free (list);

  g_print ("ok\n");


  g_print ("checking singly linked lists...");

  slist = NULL;
  for (i = 0; i < 10; i++)
    slist = g_slist_append (slist, &nums[i]);
  slist = g_slist_reverse (slist);

  for (i = 0; i < 10; i++)
    {
      st = g_slist_nth (slist, i);
      if (*((gint*) st->data) != (9 - i))
	g_error ("failed");
    }

  g_slist_free (slist);
  slist = NULL;

  for (i = 0; i < 10; i++)
    slist = g_slist_insert_sorted (slist, &morenums[i], my_list_compare_one);

  /*
  g_print("\n");
  g_slist_foreach (slist, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      st = g_slist_nth (slist, i);
      if (*((gint*) st->data) != i)
         g_error ("Sorted insert failed");
    }

  g_slist_free(slist);
  slist = NULL;

  for (i = 0; i < 10; i++)
    slist = g_slist_insert_sorted (slist, &morenums[i], my_list_compare_two);

  /*
  g_print("\n");
  g_slist_foreach (slist, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      st = g_slist_nth (slist, i);
      if (*((gint*) st->data) != (9 - i))
         g_error("Sorted insert failed");
    }

  g_slist_free(slist);
  slist = NULL;

  for (i = 0; i < 10; i++)
    slist = g_slist_prepend (slist, &morenums[i]);

  slist = g_slist_sort (slist, my_list_compare_two);

  /*
  g_print("\n");
  g_slist_foreach (slist, my_list_print, NULL);
  */

  for (i = 0; i < 10; i++)
    {
      st = g_slist_nth (slist, i);
      if (*((gint*) st->data) != (9 - i))
         g_error("Sorted insert failed");
    }

  g_slist_free(slist);

  g_print ("ok\n");


  g_print ("checking binary trees...\n");

  tree = g_tree_new (my_compare);
  i = 0;
  for (j = 0; j < 10; j++, i++)
    {
      chars[i] = '0' + j;
      g_tree_insert (tree, &chars[i], &chars[i]);
    }
  for (j = 0; j < 26; j++, i++)
    {
      chars[i] = 'A' + j;
      g_tree_insert (tree, &chars[i], &chars[i]);
    }
  for (j = 0; j < 26; j++, i++)
    {
      chars[i] = 'a' + j;
      g_tree_insert (tree, &chars[i], &chars[i]);
    }

  g_print ("tree height: %d\n", g_tree_height (tree));
  g_print ("tree nnodes: %d\n", g_tree_nnodes (tree));

  g_print ("tree: ");
  g_tree_traverse (tree, my_traverse, G_IN_ORDER, NULL);
  g_print ("\n");

  for (i = 0; i < 10; i++)
    g_tree_remove (tree, &chars[i]);

  g_print ("tree height: %d\n", g_tree_height (tree));
  g_print ("tree nnodes: %d\n", g_tree_nnodes (tree));

  g_print ("tree: ");
  g_tree_traverse (tree, my_traverse, G_IN_ORDER, NULL);
  g_print ("\n");

  g_print ("ok\n");


  /* check n-way trees */
  g_node_test ();

  g_print ("checking mem chunks...");

  mem_chunk = g_mem_chunk_new ("test mem chunk", 50, 100, G_ALLOC_AND_FREE);

  for (i = 0; i < 10000; i++)
    {
      mem[i] = g_chunk_new (gchar, mem_chunk);

      for (j = 0; j < 50; j++)
	mem[i][j] = i * j;
    }

  for (i = 0; i < 10000; i++)
    {
      g_mem_chunk_free (mem_chunk, mem[i]);
    }

  g_print ("ok\n");


  g_print ("checking hash tables...");

  hash_table = g_hash_table_new (my_hash, my_hash_compare);
  for (i = 0; i < 10000; i++)
    {
      array[i] = i;
      g_hash_table_insert (hash_table, &array[i], &array[i]);
    }
  g_hash_table_foreach (hash_table, my_hash_callback, NULL);

  for (i = 0; i < 10000; i++)
    if (array[i] == 0)
      g_print ("%d\n", i);

  for (i = 0; i < 10000; i++)
    g_hash_table_remove (hash_table, &array[i]);

  for (i = 0; i < 10000; i++)
    {
      array[i] = i;
      g_hash_table_insert (hash_table, &array[i], &array[i]);
    }

  if (g_hash_table_foreach_remove (hash_table, my_hash_callback_remove, NULL) != 5000 ||
      g_hash_table_size (hash_table) != 5000)
    g_print ("bad!\n");

  g_hash_table_foreach (hash_table, my_hash_callback_remove_test, NULL);


  g_hash_table_destroy (hash_table);

  g_print ("ok\n");


  g_print ("checking string chunks...");

  string_chunk = g_string_chunk_new (1024);

  for (i = 0; i < 100000; i ++)
    {
      tmp_string = g_string_chunk_insert (string_chunk, "hi pete");

      if (strcmp ("hi pete", tmp_string) != 0)
	g_error ("string chunks are broken.\n");
    }

  tmp_string_2 = g_string_chunk_insert_const (string_chunk, tmp_string);

  g_assert (tmp_string_2 != tmp_string &&
	    strcmp(tmp_string_2, tmp_string) == 0);

  tmp_string = g_string_chunk_insert_const (string_chunk, tmp_string);

  g_assert (tmp_string_2 == tmp_string);

  g_string_chunk_free (string_chunk);

  g_print ("ok\n");


  g_print ("checking arrays...");

  garray = g_array_new (FALSE, FALSE, sizeof (gint));
  for (i = 0; i < 10000; i++)
    g_array_append_val (garray, i);

  for (i = 0; i < 10000; i++)
    if (g_array_index (garray, gint, i) != i)
      g_print ("uh oh: %d ( %d )\n", g_array_index (garray, gint, i), i);

  g_array_free (garray, TRUE);

  garray = g_array_new (FALSE, FALSE, sizeof (gint));
  for (i = 0; i < 100; i++)
    g_array_prepend_val (garray, i);

  for (i = 0; i < 100; i++)
    if (g_array_index (garray, gint, i) != (100 - i - 1))
      g_print ("uh oh: %d ( %d )\n", g_array_index (garray, gint, i), 100 - i - 1);

  g_array_free (garray, TRUE);

  g_print ("ok\n");


  g_print ("checking strings...");

  string1 = g_string_new ("hi pete!");
  string2 = g_string_new ("");

  g_assert (strcmp ("hi pete!", string1->str) == 0);

  for (i = 0; i < 10000; i++)
    g_string_append_c (string1, 'a'+(i%26));

#if !(defined (_MSC_VER) || defined (__LCC__))
  /* MSVC and LCC use the same run-time C library, which doesn't like
     the %10000.10000f format... */
  g_string_sprintf (string2, "%s|%0100d|%s|%s|%0*d|%*.*f|%10000.10000f",
		    "this pete guy sure is a wuss, like he's the number ",
		    1,
		    " wuss.  everyone agrees.\n",
		    string1->str,
		    10, 666, 15, 15, 666.666666666, 666.666666666);
#else
  g_string_sprintf (string2, "%s|%0100d|%s|%s|%0*d|%*.*f|%100.100f",
		    "this pete guy sure is a wuss, like he's the number ",
		    1,
		    " wuss.  everyone agrees.\n",
		    string1->str,
		    10, 666, 15, 15, 666.666666666, 666.666666666);
#endif

  g_print ("string2 length = %d...\n", string2->len);
  string2->str[70] = '\0';
  g_print ("first 70 chars:\n%s\n", string2->str);
  string2->str[141] = '\0';
  g_print ("next 70 chars:\n%s\n", string2->str+71);
  string2->str[212] = '\0';
  g_print ("and next 70:\n%s\n", string2->str+142);
  g_print ("last 70 chars:\n%s\n", string2->str+string2->len - 70);

  g_print ("ok\n");

  g_print ("checking timers...\n");

  timer = g_timer_new ();
  g_print ("  spinning for 3 seconds...\n");

  g_timer_start (timer);
  while (g_timer_elapsed (timer, NULL) < 3)
    ;

  g_timer_stop (timer);
  g_timer_destroy (timer);

  g_print ("ok\n");

  g_print ("checking g_strcasecmp...");
  g_assert (g_strcasecmp ("FroboZZ", "frobozz") == 0);
  g_assert (g_strcasecmp ("frobozz", "frobozz") == 0);
  g_assert (g_strcasecmp ("frobozz", "FROBOZZ") == 0);
  g_assert (g_strcasecmp ("FROBOZZ", "froboz") != 0);
  g_assert (g_strcasecmp ("", "") == 0);
  g_assert (g_strcasecmp ("!#%&/()", "!#%&/()") == 0);
  g_assert (g_strcasecmp ("a", "b") < 0);
  g_assert (g_strcasecmp ("a", "B") < 0);
  g_assert (g_strcasecmp ("A", "b") < 0);
  g_assert (g_strcasecmp ("A", "B") < 0);
  g_assert (g_strcasecmp ("b", "a") > 0);
  g_assert (g_strcasecmp ("b", "A") > 0);
  g_assert (g_strcasecmp ("B", "a") > 0);
  g_assert (g_strcasecmp ("B", "A") > 0);

  g_print ("ok\n");

  g_print ("checking g_strdup...");
  g_assert(g_strdup(NULL) == NULL);
  string = g_strdup(GLIB_TEST_STRING);
  g_assert(string != NULL);
  g_assert(strcmp(string, GLIB_TEST_STRING) == 0);
  g_free(string);

  g_print ("ok\n");

  g_print ("checking g_strconcat...");
  string = g_strconcat(GLIB_TEST_STRING, NULL);
  g_assert(string != NULL);
  g_assert(strcmp(string, GLIB_TEST_STRING) == 0);
  g_free(string);
  string = g_strconcat(GLIB_TEST_STRING, GLIB_TEST_STRING,
  		       GLIB_TEST_STRING, NULL);
  g_assert(string != NULL);
  g_assert(strcmp(string, GLIB_TEST_STRING GLIB_TEST_STRING
  			  GLIB_TEST_STRING) == 0);
  g_free(string);

  g_print ("ok\n");

  g_print ("checking g_strdup_printf...");
  string = g_strdup_printf ("%05d %-5s", 21, "test");
  g_assert (string != NULL);
  g_assert (strcmp(string, "00021 test ") == 0);
  g_free (string);

  g_print ("ok\n");

  /* g_debug (argv[0]); */

  /* Relation tests */

  g_print ("checking relations...");

  relation = g_relation_new (2);

  g_relation_index (relation, 0, g_int_hash, g_int_equal);
  g_relation_index (relation, 1, g_int_hash, g_int_equal);

  for (i = 0; i < 1024; i += 1)
    data[i] = i;

  for (i = 1; i < 1023; i += 1)
    {
      g_relation_insert (relation, data + i, data + i + 1);
      g_relation_insert (relation, data + i, data + i - 1);
    }

  for (i = 2; i < 1022; i += 1)
    {
      g_assert (! g_relation_exists (relation, data + i, data + i));
      g_assert (! g_relation_exists (relation, data + i, data + i + 2));
      g_assert (! g_relation_exists (relation, data + i, data + i - 2));
    }

  for (i = 1; i < 1023; i += 1)
    {
      g_assert (g_relation_exists (relation, data + i, data + i + 1));
      g_assert (g_relation_exists (relation, data + i, data + i - 1));
    }

  for (i = 2; i < 1022; i += 1)
    {
      g_assert (g_relation_count (relation, data + i, 0) == 2);
      g_assert (g_relation_count (relation, data + i, 1) == 2);
    }

  g_assert (g_relation_count (relation, data, 0) == 0);

  g_assert (g_relation_count (relation, data + 42, 0) == 2);
  g_assert (g_relation_count (relation, data + 43, 1) == 2);
  g_assert (g_relation_count (relation, data + 41, 1) == 2);
  g_relation_delete (relation, data + 42, 0);
  g_assert (g_relation_count (relation, data + 42, 0) == 0);
  g_assert (g_relation_count (relation, data + 43, 1) == 1);
  g_assert (g_relation_count (relation, data + 41, 1) == 1);

  tuples = g_relation_select (relation, data + 200, 0);

  g_assert (tuples->len == 2);

#if 0
  for (i = 0; i < tuples->len; i += 1)
    {
      printf ("%d %d\n",
	      *(gint*) g_tuples_index (tuples, i, 0),
	      *(gint*) g_tuples_index (tuples, i, 1));
    }
#endif

  g_assert (g_relation_exists (relation, data + 300, data + 301));
  g_relation_delete (relation, data + 300, 0);
  g_assert (!g_relation_exists (relation, data + 300, data + 301));

  g_tuples_destroy (tuples);

  g_relation_destroy (relation);

  relation = NULL;

  g_print ("ok\n");

  g_print ("checking pointer arrays...");

  gparray = g_ptr_array_new ();
  for (i = 0; i < 10000; i++)
    g_ptr_array_add (gparray, GINT_TO_POINTER (i));

  for (i = 0; i < 10000; i++)
    if (g_ptr_array_index (gparray, i) != GINT_TO_POINTER (i))
      g_print ("array fails: %p ( %p )\n", g_ptr_array_index (gparray, i), GINT_TO_POINTER (i));

  g_ptr_array_free (gparray, TRUE);

  g_print ("ok\n");


  g_print ("checking byte arrays...");

  gbarray = g_byte_array_new ();
  for (i = 0; i < 10000; i++)
    g_byte_array_append (gbarray, (guint8*) "abcd", 4);

  for (i = 0; i < 10000; i++)
    {
      g_assert (gbarray->data[4*i] == 'a');
      g_assert (gbarray->data[4*i+1] == 'b');
      g_assert (gbarray->data[4*i+2] == 'c');
      g_assert (gbarray->data[4*i+3] == 'd');
    }

  g_byte_array_free (gbarray, TRUE);
  g_print ("ok\n");

  g_printerr ("g_log tests:");
  g_warning ("harmless warning with parameters: %d %s %#x", 42, "Boo", 12345);
  g_message ("the next warning is a test:");
  string = NULL;
  g_print (string);

  g_print ("checking endian macros (host is ");
#if G_BYTE_ORDER == G_BIG_ENDIAN
  g_print ("big endian)...");
#else
  g_print ("little endian)...");
#endif
  g_assert (GUINT16_SWAP_LE_BE (gu16t1) == gu16t2);
  g_assert (GUINT32_SWAP_LE_BE (gu32t1) == gu32t2);
#ifdef G_HAVE_GINT64
  g_assert (GUINT64_SWAP_LE_BE (gu64t1) == gu64t2);
#endif
  g_print ("ok\n");

  return 0;
}
示例#28
0
static void
_connection_handler(xmpp_conn_t *const conn, const xmpp_conn_event_t status, const int error,
    xmpp_stream_error_t *const stream_error, void *const userdata)
{
    // login success
    if (status == XMPP_CONN_CONNECT) {
        log_debug("Connection handler: XMPP_CONN_CONNECT");
        jabber_conn.conn_status = JABBER_CONNECTED;

        int secured = xmpp_conn_is_secured(jabber_conn.conn);

        // logged in with account
        if (saved_account.name) {
            log_debug("Connection handler: logged in with account name: %s", saved_account.name);
            sv_ev_login_account_success(saved_account.name, secured);

        // logged in without account, use details to create new account
        } else {
            log_debug("Connection handler: logged in with jid: %s", saved_details.name);
            accounts_add(saved_details.name, saved_details.altdomain, saved_details.port, saved_details.tls_policy);
            accounts_set_jid(saved_details.name, saved_details.jid);

            sv_ev_login_account_success(saved_details.name, secured);
            saved_account.name = strdup(saved_details.name);
            saved_account.passwd = strdup(saved_details.passwd);

            _connection_free_saved_details();
        }

        Jid *my_jid = jid_create(jabber_get_fulljid());
        jabber_conn.domain = strdup(my_jid->domainpart);
        jid_destroy(my_jid);

        chat_sessions_init();

        roster_add_handlers();
        message_add_handlers();
        presence_add_handlers();
        iq_add_handlers();

        roster_request();
        bookmark_request();

        if (prefs_get_boolean(PREF_CARBONS)){
            iq_enable_carbons();
        }

        if ((prefs_get_reconnect() != 0) && reconnect_timer) {
            g_timer_destroy(reconnect_timer);
            reconnect_timer = NULL;
        }

    } else if (status == XMPP_CONN_DISCONNECT) {
        log_debug("Connection handler: XMPP_CONN_DISCONNECT");

        // lost connection for unknown reason
        if (jabber_conn.conn_status == JABBER_CONNECTED) {
            log_debug("Connection handler: Lost connection for unknown reason");
            sv_ev_lost_connection();
            if (prefs_get_reconnect() != 0) {
                assert(reconnect_timer == NULL);
                reconnect_timer = g_timer_new();
                // free resources but leave saved_user untouched
                _connection_free_session_data();
            } else {
                _connection_free_saved_account();
                _connection_free_saved_details();
                _connection_free_session_data();
            }

        // login attempt failed
        } else if (jabber_conn.conn_status != JABBER_DISCONNECTING) {
            log_debug("Connection handler: Login failed");
            if (reconnect_timer == NULL) {
                log_debug("Connection handler: No reconnect timer");
                sv_ev_failed_login();
                _connection_free_saved_account();
                _connection_free_saved_details();
                _connection_free_session_data();
            } else {
                log_debug("Connection handler: Restarting reconnect timer");
                if (prefs_get_reconnect() != 0) {
                    g_timer_start(reconnect_timer);
                }
                // free resources but leave saved_user untouched
                _connection_free_session_data();
            }
        }

        // close stream response from server after disconnect is handled too
        jabber_conn.conn_status = JABBER_DISCONNECTED;
    } else if (status == XMPP_CONN_FAIL) {
        log_debug("Connection handler: XMPP_CONN_FAIL");
    } else {
        log_error("Connection handler: Unknown status");
    }
}
示例#29
0
gint main (gint argc, gchar **argv)
{
	PopplerDocument  *document;
	GtkWidget        *win;
	GtkWidget        *hbox;
	GtkWidget        *notebook;
	GtkWidget        *treeview;
	GtkTreeSelection *selection;
	GFile            *file;
	gchar            *uri;
	GTimer           *timer;
	GError           *error = NULL;

	if (argc != 2) {
		g_print ("Usage: poppler-glib-demo FILE\n");
		return 1;
	}

	if (!g_thread_supported ())
		g_thread_init (NULL);

	gtk_init (&argc, &argv);

	file = g_file_new_for_commandline_arg (argv[1]);
	uri = g_file_get_uri (file);

	timer = g_timer_new ();
	document = poppler_document_new_from_file (uri, NULL, &error);
	g_timer_stop (timer);
	if (error) {
		while (g_error_matches (error, POPPLER_ERROR, POPPLER_ERROR_ENCRYPTED)) {
			GtkDialog   *dialog;
			const gchar *password;

			dialog = pgd_demo_get_auth_dialog (file);
			if (gtk_dialog_run (dialog) != GTK_RESPONSE_OK) {
				g_print ("Error: no password provided\n");
				g_object_unref (file);
				g_free (uri);

				return 1;
			}

			g_clear_error (&error);
			password = g_object_get_data (G_OBJECT (dialog), "pgd-password");

			g_timer_start (timer);
			document = poppler_document_new_from_file (uri, password, &error);
			g_timer_stop (timer);

			gtk_widget_destroy (GTK_WIDGET (dialog));
		}

		if (error) {
			g_print ("Error: %s\n", error->message);
			g_error_free (error);
			g_object_unref (file);
			g_free (uri);

			return 1;
		}
	}

	g_object_unref (file);
	g_free (uri);

	g_print ("Document successfully loaded in %.4f seconds\n",
		 g_timer_elapsed (timer, NULL));
	g_timer_destroy (timer);

	/* Main window */
	win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_default_size (GTK_WINDOW (win), 600, 600);
	gtk_window_set_title (GTK_WINDOW (win), "Poppler GLib Demo");
	g_signal_connect (G_OBJECT (win), "delete-event",
			  G_CALLBACK (gtk_main_quit), NULL);

	hbox = gtk_hbox_new (FALSE, 6);

	treeview = pgd_demo_list_create ();
	gtk_box_pack_start (GTK_BOX (hbox), treeview, FALSE, TRUE, 0);
	gtk_widget_show (treeview);
	
	notebook = pdg_demo_notebook_create (document);
	gtk_box_pack_start (GTK_BOX (hbox), notebook, TRUE, TRUE, 0);
	gtk_widget_show (notebook);

	selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
	g_signal_connect (G_OBJECT (selection), "changed",
			  G_CALLBACK (pgd_demo_changed),
			  (gpointer) notebook);

	gtk_container_add (GTK_CONTAINER (win), hbox);
	gtk_widget_show (hbox);
	
	gtk_widget_show (win);

	gtk_main ();

	g_object_unref (document);
	
	return 0;
}
示例#30
0
/**
 * Scan for Metrahit 2x in a bidirectional mode using Gossen Metrawatt
 * 'BD 232' interface.
 */
static GSList *scan_2x_bd232(struct sr_dev_driver *di, GSList *options)
{
	struct sr_dev_inst *sdi;
	struct drv_context *drvc;
	struct dev_context *devc;
	struct sr_config *src;
	struct sr_serial_dev_inst *serial;
	GSList *l, *devices;
	const char *conn, *serialcomm;
	int cnt, byte;
	gint64 timeout_us;

	sdi = NULL;
	devc = NULL;
	conn = serialcomm = NULL;
	devices = NULL;

	drvc = di->context;
	drvc->instances = NULL;

	sr_spew("scan_2x_bd232() called!");

	for (l = options; l; l = l->next) {
		src = l->data;
		switch (src->key) {
		case SR_CONF_CONN:
			conn = g_variant_get_string(src->data, NULL);
			break;
		case SR_CONF_SERIALCOMM:
			serialcomm = g_variant_get_string(src->data, NULL);
			break;
		}
	}
	if (!conn)
		return NULL;
	if (!serialcomm)
		serialcomm = SERIALCOMM_2X;

	serial = sr_serial_dev_inst_new(conn, serialcomm);

	if (serial_open(serial, SERIAL_RDWR) != SR_OK)
		goto exit_err;

	devc = g_malloc0(sizeof(struct dev_context));

	sdi = g_malloc0(sizeof(struct sr_dev_inst));
	sdi->status = SR_ST_INACTIVE;
	sdi->vendor = g_strdup(VENDOR_GMC);
	sdi->priv = devc;

	/* Send message 03 "Query multimeter version and status" */
	sdi->conn = serial;
	sdi->priv = devc;
	if (req_stat14(sdi, TRUE) != SR_OK)
		goto exit_err;

	/* Wait for reply from device(s) for up to 2s. */
	timeout_us = g_get_monotonic_time() + (2 * 1000 * 1000);

	while (timeout_us > g_get_monotonic_time()) {
		/* Receive reply (14 bytes) */
		devc->buflen = 0;
		for (cnt = 0; cnt < GMC_REPLY_SIZE; cnt++) {
			byte = read_byte(serial, timeout_us);
			if (byte != -1)
				devc->buf[devc->buflen++] = (byte & MASK_6BITS);
		}

		if (devc->buflen != GMC_REPLY_SIZE)
			continue;

		devc->addr = devc->buf[0];
		process_msg14(sdi);
		devc->buflen = 0;

		if (devc->model != METRAHIT_NONE) {
			sr_spew("%s %s detected!", VENDOR_GMC, gmc_model_str(devc->model));
			devc->elapsed_msec = g_timer_new();
			sdi->model = g_strdup(gmc_model_str(devc->model));
			sdi->version = g_strdup_printf("Firmware %d.%d", devc->fw_ver_maj, devc->fw_ver_min);
			sdi->conn = serial;
			sdi->priv = devc;
			sdi->driver = di;
			sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "P1");
			drvc->instances = g_slist_append(drvc->instances, sdi);
			devices = g_slist_append(devices, sdi);
			devc = g_malloc0(sizeof(struct dev_context));
			sdi = g_malloc0(sizeof(struct sr_dev_inst));
			sdi->status = SR_ST_INACTIVE;
			sdi->vendor = g_strdup(VENDOR_GMC);
		}
	};

	/* Free last alloc if no device found */
	if (devc->model == METRAHIT_NONE) {
		g_free(devc);
		sr_dev_inst_free(sdi);
	}

	return devices;

exit_err:
	sr_info("scan_2x_bd232(): Error!");

	if (serial)
		sr_serial_dev_inst_free(serial);
	g_free(devc);
	if (sdi)
		sr_dev_inst_free(sdi);

	return NULL;
}