Exemple #1
0
/**
 * mono_process_get_name:
 * @pid: pid of the process
 * @buf: byte buffer where to store the name of the prcoess
 * @len: size of the buffer @buf
 *
 * Return the name of the process identified by @pid, storing it
 * inside @buf for a maximum of len bytes (including the terminating 0).
 */
char*
mono_process_get_name (gpointer pid, char *buf, int len)
{
#if USE_SYSCTL
	int res;
#ifdef KERN_PROC2
	int mib [6];
	size_t data_len = sizeof (struct kinfo_proc2);
	struct kinfo_proc2 processi;
#else
	int mib [4];
	size_t data_len = sizeof (struct kinfo_proc);
	struct kinfo_proc processi;
#endif /* KERN_PROC2 */

	memset (buf, 0, len);

#ifdef KERN_PROC2
	mib [0] = CTL_KERN;
	mib [1] = KERN_PROC2;
	mib [2] = KERN_PROC_PID;
	mib [3] = GPOINTER_TO_UINT (pid);
	mib [4] = sizeof(struct kinfo_proc2);
	mib [5] = 400; /* XXX */

	res = sysctl (mib, 6, &processi, &data_len, NULL, 0);

	if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
		return buf;
	}
#else
	mib [0] = CTL_KERN;
	mib [1] = KERN_PROC;
	mib [2] = KERN_PROC_PID;
	mib [3] = GPOINTER_TO_UINT (pid);
	
	res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
	if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
		return buf;
	}
#endif /* KERN_PROC2 */
	strncpy (buf, processi.kinfo_name_member, len - 1);
	return buf;
#else
	char fname [128];
	FILE *file;
	char *p;
	int r;
	sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
	buf [0] = 0;
	file = fopen (fname, "r");
	if (!file)
		return buf;
	r = fread (buf, 1, len - 1, file);
	fclose (file);
	buf [r] = 0;
	p = strrchr (buf, '/');
	if (p)
		return p + 1;
	if (r == 0) {
		return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
	}
	return buf;
#endif
}
Exemple #2
0
/*
 * mono_debug_symfile_get_line_numbers_full:
 *
 * On return, SOURCE_FILE_LIST will point to a GPtrArray of MonoDebugSourceFile
 * structures, and SOURCE_FILES will contain indexes into this array.
 * The MonoDebugSourceFile structures are owned by this module.
 */
void
mono_debug_symfile_get_line_numbers_full (MonoDebugMethodInfo *minfo, char **source_file, GPtrArray **source_file_list, int *n_il_offsets, int **il_offsets, int **line_numbers, int **source_files)
{
    // FIXME: Unify this with mono_debug_symfile_lookup_location
    MonoSymbolFile *symfile;
    const unsigned char *ptr;
    StatementMachine stm;
    uint32_t i;
    GPtrArray *il_offset_array, *line_number_array, *source_file_array;

    if (source_file_list)
        *source_file_list = NULL;
    if (n_il_offsets)
        *n_il_offsets = 0;
    if (source_files)
        *source_files = NULL;
    if (source_file)
        *source_file = NULL;

    if ((symfile = minfo->handle->symfile) == NULL)
        return;

    il_offset_array = g_ptr_array_new ();
    line_number_array = g_ptr_array_new ();
    source_file_array = g_ptr_array_new ();

    stm.line_base = read32 (&symfile->offset_table->_line_number_table_line_base);
    stm.line_range = read32 (&symfile->offset_table->_line_number_table_line_range);
    stm.opcode_base = (uint8_t) read32 (&symfile->offset_table->_line_number_table_opcode_base);
    stm.max_address_incr = (255 - stm.opcode_base) / stm.line_range;

    mono_debugger_lock ();

    ptr = symfile->raw_contents + minfo->lnt_offset;

    stm.symfile = symfile;
    stm.offset = stm.last_offset = 0;
    stm.last_file = 0;
    stm.last_line = 0;
    stm.first_file = 0;
    stm.file = 1;
    stm.line = 1;
    stm.is_hidden = FALSE;

    while (TRUE) {
        uint8_t opcode = *ptr++;

        if (opcode == 0) {
            uint8_t size = *ptr++;
            const unsigned char *end_ptr = ptr + size;

            opcode = *ptr++;

            if (opcode == DW_LNE_end_sequence) {
                if (il_offset_array->len == 0)
                    /* Empty table */
                    break;
                add_line (&stm, il_offset_array, line_number_array, source_file_array);
                break;
            } else if (opcode == DW_LNE_MONO_negate_is_hidden) {
                stm.is_hidden = !stm.is_hidden;
            } else if ((opcode >= DW_LNE_MONO__extensions_start) &&
                       (opcode <= DW_LNE_MONO__extensions_end)) {
                ; // reserved for future extensions
            } else {
                g_warning ("Unknown extended opcode %x in LNT", opcode);
            }

            ptr = end_ptr;
            continue;
        } else if (opcode < stm.opcode_base) {
            switch (opcode) {
            case DW_LNS_copy:
                add_line (&stm, il_offset_array, line_number_array, source_file_array);
                break;
            case DW_LNS_advance_pc:
                stm.offset += read_leb128 (ptr, &ptr);
                break;
            case DW_LNS_advance_line:
                stm.line += read_leb128 (ptr, &ptr);
                break;
            case DW_LNS_set_file:
                stm.file = read_leb128 (ptr, &ptr);
                break;
            case DW_LNS_const_add_pc:
                stm.offset += stm.max_address_incr;
                break;
            default:
                g_warning ("Unknown standard opcode %x in LNT", opcode);
                g_assert_not_reached ();
            }
        } else {
            opcode -= stm.opcode_base;

            stm.offset += opcode / stm.line_range;
            stm.line += stm.line_base + (opcode % stm.line_range);

            add_line (&stm, il_offset_array, line_number_array, source_file_array);
        }
    }

    if (!stm.file && stm.first_file)
        stm.file = stm.first_file;

    if (stm.file && source_file) {
        int offset = read32(&(stm.symfile->offset_table->_source_table_offset)) +
                     (stm.file - 1) * sizeof (MonoSymbolFileSourceEntry);
        MonoSymbolFileSourceEntry *se = (MonoSymbolFileSourceEntry *)
                                        (stm.symfile->raw_contents + offset);

        if (source_file)
            *source_file = read_string (stm.symfile->raw_contents + read32(&(se->_data_offset)), NULL);
    }

    if (source_file_list) {
        int file, last_file = 0;

        *source_file_list = g_ptr_array_new ();
        if (source_files)
            *source_files = g_malloc (il_offset_array->len * sizeof (int));

        for (i = 0; i < il_offset_array->len; ++i) {
            file = GPOINTER_TO_UINT (g_ptr_array_index (source_file_array, i));
            if (file && file != last_file) {
                MonoDebugSourceInfo *info = get_source_info (symfile, file);

                g_ptr_array_add (*source_file_list, info);
            }
            last_file = file;
            if (source_files)
                (*source_files) [i] = (*source_file_list)->len - 1;
        }
        if ((*source_file_list)->len == 0 && stm.file) {
            MonoDebugSourceInfo *info = get_source_info (symfile, stm.file);

            g_ptr_array_add (*source_file_list, info);
        }
    }

    if (n_il_offsets)
        *n_il_offsets = il_offset_array->len;
    if (il_offsets && line_numbers) {
        *il_offsets = g_malloc (il_offset_array->len * sizeof (int));
        *line_numbers = g_malloc (il_offset_array->len * sizeof (int));
        for (i = 0; i < il_offset_array->len; ++i) {
            (*il_offsets) [i] = GPOINTER_TO_UINT (g_ptr_array_index (il_offset_array, i));
            (*line_numbers) [i] = GPOINTER_TO_UINT (g_ptr_array_index (line_number_array, i));
        }
    }
    g_ptr_array_free (il_offset_array, TRUE);
    g_ptr_array_free (line_number_array, TRUE);

    mono_debugger_unlock ();
    return;
}
int main(int argc, char * argv[]){
    int i = 1;
    const char * k_mixture_model_filename = NULL;

    setlocale(LC_ALL, "");
    while ( i < argc ){
        if ( strcmp("--help", argv[i]) == 0 ){
            print_help();
            exit(0);
        } else if ( strcmp("--skip-pi-gram-training", argv[i]) == 0 ){
            g_train_pi_gram = false;
        } else if ( strcmp("--maximum-occurs-allowed", argv[i]) == 0 ){
            if ( ++i >= argc ){
                print_help();
                exit(EINVAL);
            }
            g_maximum_occurs = atoi(argv[i]);
        } else if ( strcmp("--maximum-increase-rates-allowed", argv[i]) == 0 ){
            if ( ++i >= argc ){
                print_help();
                exit(EINVAL);
            }
            g_maximum_increase_rates = atof(argv[i]);
        } else if ( strcmp("--k-mixture-model-file", argv[i]) == 0 ){
            if ( ++i >= argc ){
                print_help();
                exit(EINVAL);
            }
            k_mixture_model_filename = argv[i];
        } else {
            break;
        }
        ++i;
    }

    PhraseLargeTable2 phrase_table;
    MemoryChunk * chunk = new MemoryChunk;
    chunk->load("phrase_index.bin");
    phrase_table.load(chunk);

    FacadePhraseIndex phrase_index;
    if (!load_phrase_index(&phrase_index))
        exit(ENOENT);

    KMixtureModelBigram bigram(K_MIXTURE_MODEL_MAGIC_NUMBER);
    bigram.attach(k_mixture_model_filename, ATTACH_READWRITE|ATTACH_CREATE);

    while ( i < argc ){
        const char * filename = argv[i];
        FILE * document = fopen(filename, "r");
        if ( NULL == document ){
            int err_saved = errno;
            fprintf(stderr, "can't open file: %s.\n", filename);
            fprintf(stderr, "error:%s.\n", strerror(err_saved));
            exit(err_saved);
        }

        HashofDocument hash_of_document = g_hash_table_new
            (g_direct_hash, g_direct_equal);
        HashofUnigram hash_of_unigram = g_hash_table_new
            (g_direct_hash, g_direct_equal);

        assert(read_document(&phrase_table, &phrase_index, document,
                             hash_of_document, hash_of_unigram));
        fclose(document);
        document = NULL;

        GHashTableIter iter;
        gpointer key, value;

        /* train the document, and convert it to k mixture model. */
        g_hash_table_iter_init(&iter, hash_of_document);
        while (g_hash_table_iter_next(&iter, &key, &value)) {
            phrase_token_t token1 = GPOINTER_TO_UINT(key);
            train_second_word(hash_of_unigram, &bigram,
                              hash_of_document, token1);
        }

        KMixtureModelMagicHeader magic_header;
        assert(bigram.get_magic_header(magic_header));
        magic_header.m_N ++;
        assert(bigram.set_magic_header(magic_header));

        post_processing_unigram(&bigram, hash_of_unigram);

        /* free resources of g_hash_of_document */
        g_hash_table_iter_init(&iter, hash_of_document);
        while (g_hash_table_iter_next(&iter, &key, &value)) {
            HashofSecondWord second_word = (HashofSecondWord) value;
            g_hash_table_iter_steal(&iter);
            g_hash_table_unref(second_word);
        }
        g_hash_table_unref(hash_of_document);
        hash_of_document = NULL;

        g_hash_table_unref(hash_of_unigram);
        hash_of_unigram = NULL;

        ++i;
    }

    return 0;
}
Exemple #4
0
void fill_initial_rtpe_cfg(struct rtpengine_config* ini_rtpe_cfg) {

	GList* l;
	struct intf_config* gptr_data;

	for(l = rtpe_config.interfaces.head; l ; l=l->next) {
		gptr_data = (struct intf_config*)malloc(sizeof(struct intf_config));
		memcpy(gptr_data, (struct intf_config*)(l->data), sizeof(struct intf_config));

		g_queue_push_tail(&ini_rtpe_cfg->interfaces, gptr_data);
	}

	for(l = rtpe_config.redis_subscribed_keyspaces.head; l ; l = l->next) {
		// l->data has been assigned to a variable before being given into the queue structure not to get a shallow copy
		unsigned int num = GPOINTER_TO_UINT(l->data);
		g_queue_push_tail(&ini_rtpe_cfg->redis_subscribed_keyspaces, GINT_TO_POINTER(num));
	}

	ini_rtpe_cfg->kernel_table = rtpe_config.kernel_table;
	ini_rtpe_cfg->max_sessions = rtpe_config.max_sessions;
	ini_rtpe_cfg->cpu_limit = rtpe_config.cpu_limit;
	ini_rtpe_cfg->load_limit = rtpe_config.load_limit;
	ini_rtpe_cfg->bw_limit = rtpe_config.bw_limit;
	ini_rtpe_cfg->timeout = rtpe_config.timeout;
	ini_rtpe_cfg->silent_timeout = rtpe_config.silent_timeout;
	ini_rtpe_cfg->offer_timeout = rtpe_config.offer_timeout;
	ini_rtpe_cfg->final_timeout = rtpe_config.final_timeout;
	ini_rtpe_cfg->delete_delay = rtpe_config.delete_delay;
	ini_rtpe_cfg->redis_expires_secs = rtpe_config.redis_expires_secs;
	ini_rtpe_cfg->default_tos = rtpe_config.default_tos;
	ini_rtpe_cfg->control_tos = rtpe_config.control_tos;
	ini_rtpe_cfg->graphite_interval = rtpe_config.graphite_interval;
	ini_rtpe_cfg->redis_num_threads = rtpe_config.redis_num_threads;
	ini_rtpe_cfg->homer_protocol = rtpe_config.homer_protocol;
	ini_rtpe_cfg->homer_id = rtpe_config.homer_id;
	ini_rtpe_cfg->no_fallback = rtpe_config.no_fallback;
	ini_rtpe_cfg->port_min = rtpe_config.port_min;
	ini_rtpe_cfg->port_max = rtpe_config.port_max;
	ini_rtpe_cfg->redis_db = rtpe_config.redis_db;
	ini_rtpe_cfg->redis_write_db = rtpe_config.redis_write_db;
	ini_rtpe_cfg->no_redis_required = rtpe_config.no_redis_required;
	ini_rtpe_cfg->num_threads = rtpe_config.num_threads;
	ini_rtpe_cfg->media_num_threads = rtpe_config.media_num_threads;
	ini_rtpe_cfg->fmt = rtpe_config.fmt;
	ini_rtpe_cfg->log_format = rtpe_config.log_format;
	ini_rtpe_cfg->redis_allowed_errors = rtpe_config.redis_allowed_errors;
	ini_rtpe_cfg->redis_disable_time = rtpe_config.redis_disable_time;
	ini_rtpe_cfg->redis_cmd_timeout = rtpe_config.redis_cmd_timeout;
	ini_rtpe_cfg->redis_connect_timeout = rtpe_config.redis_connect_timeout;
	ini_rtpe_cfg->common.log_level = rtpe_config.common.log_level;

	ini_rtpe_cfg->graphite_ep = rtpe_config.graphite_ep;
	ini_rtpe_cfg->tcp_listen_ep = rtpe_config.tcp_listen_ep;
	ini_rtpe_cfg->udp_listen_ep = rtpe_config.udp_listen_ep;
	ini_rtpe_cfg->ng_listen_ep = rtpe_config.ng_listen_ep;
	ini_rtpe_cfg->cli_listen_ep = rtpe_config.cli_listen_ep;
	ini_rtpe_cfg->redis_ep = rtpe_config.redis_ep;
	ini_rtpe_cfg->redis_write_ep = rtpe_config.redis_write_ep;
	ini_rtpe_cfg->homer_ep = rtpe_config.homer_ep;

	ini_rtpe_cfg->b2b_url = g_strdup(rtpe_config.b2b_url);
	ini_rtpe_cfg->redis_auth = g_strdup(rtpe_config.redis_auth);
	ini_rtpe_cfg->redis_write_auth = g_strdup(rtpe_config.redis_write_auth);
	ini_rtpe_cfg->spooldir = g_strdup(rtpe_config.spooldir);
	ini_rtpe_cfg->iptables_chain = g_strdup(rtpe_config.iptables_chain);
	ini_rtpe_cfg->rec_method = g_strdup(rtpe_config.rec_method);
	ini_rtpe_cfg->rec_format = g_strdup(rtpe_config.rec_format);

}
static guint
ata_cmd_hash_matched(gconstpointer k)
{
  return GPOINTER_TO_UINT(k);
}
Exemple #6
0
/* hash func */
static guint fragment_hash_func(gconstpointer k)
{
    const fragment_key_t *key = (const fragment_key_t *)k;
    return (GPOINTER_TO_UINT(key->stream)) + ((guint)key -> framenum) + ((guint)key->offset);
}
Exemple #7
0
static void
remove_pulse (gpointer pulse_id)
{
  g_source_remove (GPOINTER_TO_UINT (pulse_id));
}
Exemple #8
0
static char* expand_terminal(char* cmd, gboolean keep_open, GError** error)
{
    FmTerminal* term;
    const char* opts;
    char* ret;
    /* if %s is not found, fallback to -e */
    static FmTerminal xterm_def = { .program = "xterm", .open_arg = "-e" };

    term = fm_terminal_dup_default(NULL);
    /* bug #3457335: Crash on application start with Terminal=true. */
    if(!term) /* fallback to xterm if a terminal emulator is not found. */
    {
        /* FIXME: we should not hard code xterm here. :-(
         * It's better to prompt the user and let he or she set
         * his preferred terminal emulator. */
        term = &xterm_def;
    }
    if(keep_open && term->noclose_arg)
        opts = term->noclose_arg;
    else
        opts = term->open_arg;
    if(term->custom_args)
        ret = g_strdup_printf("%s %s %s %s", term->program, term->custom_args,
                              opts, cmd);
    else
        ret = g_strdup_printf("%s %s %s", term->program, opts, cmd);
    if(term != &xterm_def)
        g_object_unref(term);
    return ret;
}

static gboolean do_launch(GAppInfo* appinfo, const char* full_desktop_path, GKeyFile* kf, GList* gfiles, GAppLaunchContext* ctx, GError** err)
{
    gboolean ret = FALSE;
    char* cmd, *path;
    char** argv;
    int argc;
    gboolean use_terminal;
    GAppInfoCreateFlags flags;

    cmd = expand_exec_macros(appinfo, full_desktop_path, kf, gfiles);
    if(G_LIKELY(kf))
        use_terminal = g_key_file_get_boolean(kf, "Desktop Entry", "Terminal", NULL);
    else
    {
        flags = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(appinfo), "flags"));
        use_terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
    }

    if(use_terminal)
    {
        /* FIXME: is it right key to mark this option? */
        gboolean keep_open = FALSE;
        char* term_cmd;

        if(G_LIKELY(kf))
            keep_open = g_key_file_get_boolean(kf, "Desktop Entry",
                                               "X-KeepTerminal", NULL);
        term_cmd = expand_terminal(cmd, keep_open, err);
        g_free(cmd);
        if(!term_cmd)
            return FALSE;
        cmd = term_cmd;
    }

    g_debug("launch command: <%s>", cmd);
    if(g_shell_parse_argv(cmd, &argc, &argv, err))
    {
        struct ChildSetup data;
        if(ctx)
        {
            gboolean use_sn;
            if(G_LIKELY(kf) && g_key_file_has_key(kf, "Desktop Entry", "StartupNotify", NULL))
                use_sn = g_key_file_get_boolean(kf, "Desktop Entry", "StartupNotify", NULL);
            else if(fm_config->force_startup_notify)
            {
                /* if the app doesn't explicitly ask us not to use sn,
                 * and fm_config->force_startup_notify is TRUE, then
                 * use it by default, unless it's a console app. */
                use_sn = !use_terminal; /* we only use sn for GUI apps by default */
                /* FIXME: console programs should use sn_id of terminal emulator instead. */
            }
            else
                use_sn = FALSE;
            data.display = g_app_launch_context_get_display(ctx, appinfo, gfiles);

            if(use_sn)
                data.sn_id = g_app_launch_context_get_startup_notify_id(ctx, appinfo, gfiles);
            else
                data.sn_id = NULL;
        }
        else
        {
            data.display = NULL;
            data.sn_id = NULL;
        }
        g_debug("sn_id = %s", data.sn_id);

        if(G_LIKELY(kf))
            path = g_key_file_get_string(kf, "Desktop Entry", "Path", NULL);
        else
            path = NULL;

        ret = g_spawn_async(path, argv, NULL,
                            G_SPAWN_SEARCH_PATH,
                            child_setup, &data, NULL, err);
        g_free(path);
        g_free(data.display);
        g_free(data.sn_id);

        g_strfreev(argv);
    }
    g_free(cmd);
    return ret;
}
Exemple #9
0
static void
delete_done_cb (LIBMTP_mtpdevice_t *device, TracksDeletedCallbackData *data)
{
	LIBMTP_folder_t *folders;
	LIBMTP_file_t *files;

	data->actually_free = FALSE;
	update_free_space_cb (device, RB_MTP_SOURCE (data->source));

	/* if any of the folders we just deleted from are now empty, delete them */
	folders = LIBMTP_Get_Folder_List (device);
	files = LIBMTP_Get_Filelisting_With_Callback (device, NULL, NULL);
	if (folders != NULL) {
		GHashTableIter iter;
		gpointer key;
		g_hash_table_iter_init (&iter, data->check_folders);
		while (g_hash_table_iter_next (&iter, &key, NULL)) {
			LIBMTP_folder_t *f;
			LIBMTP_folder_t *c;
			LIBMTP_file_t *file;
			uint32_t folder_id = GPOINTER_TO_UINT(key);

			while (folder_id != device->default_music_folder && folder_id != 0) {

				f = LIBMTP_Find_Folder (folders, folder_id);
				if (f == NULL) {
					rb_debug ("unable to find folder %u", folder_id);
					break;
				}

				/* don't delete folders with children that we didn't just delete */
				for (c = f->child; c != NULL; c = c->sibling) {
					if (g_hash_table_lookup (data->check_folders,
								 GUINT_TO_POINTER (c->folder_id)) == NULL) {
						break;
					}
				}
				if (c != NULL) {
					rb_debug ("folder %s has children", f->name);
					break;
				}

				/* don't delete folders that contain files */
				for (file = files; file != NULL; file = file->next) {
					if (file->parent_id == folder_id) {
						break;
					}
				}

				if (file != NULL) {
					rb_debug ("folder %s contains at least one file: %s", f->name, file->filename);
					break;
				}

				/* ok, the folder is empty */
				rb_debug ("deleting empty folder %s", f->name);
				LIBMTP_Delete_Object (device, f->folder_id);

				/* if the folder we just deleted has siblings, the parent
				 * can't be empty.
				 */
				if (f->sibling != NULL) {
					rb_debug ("folder %s has siblings, can't delete parent", f->name);
					break;
				}
				folder_id = f->parent_id;
			}
		}

		LIBMTP_destroy_folder_t (folders);
	} else {
		rb_debug ("unable to get device folder list");
	}

	/* clean up the file list */
	while (files != NULL) {
		LIBMTP_file_t *n;

		n = files->next;
		LIBMTP_destroy_file_t (files);
		files = n;
	}

	g_idle_add ((GSourceFunc) delete_done_idle_cb, data);
}
Exemple #10
0
int main (int argc, char* argv[])
{
	static const struct option options[] = {
		{ "action", required_argument, NULL, 'a' },
		{ "device", required_argument, NULL, 'D' },
		{ "user", required_argument, NULL, 'u' },
		{ "debug", no_argument, NULL, 'd' },
		{ "help", no_argument, NULL, 'h' },
		{}
	};
	int action = -1;
	const char *device = NULL;
	bool uid_given = false;
	uid_t uid = 0;
	uid_t uid2 = 0;
	const char* remove_session_id = NULL;
	int rc = 0;

	/* valgrind is more important to us than a slice allocator */
	g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, 1);

	while (1) {
		int option;

		option = getopt_long(argc, argv, "+a:D:u:dh", options, NULL);
		if (option == -1)
			break;

		switch (option) {
		case 'a':
			if (strcmp(optarg, "remove") == 0)
				action = ACTION_REMOVE;
			else
				action = ACTION_ADD;
			break;
		case 'D':
			device = optarg;
			break;
		case 'u':
			uid_given = true;
			uid = strtoul(optarg, NULL, 10);
			break;
		case 'd':
			debug = 1;
			break;
		case 'h':
			printf("Usage: udev-acl --action=ACTION [--device=DEVICEFILE] [--user=UID]\n\n");
			goto out;
		}
	}

	if (action < 0 && device == NULL && !uid_given)
		if (!consolekit_called(argv[optind], &uid, &uid2, &remove_session_id, &action))
			uid_given = true;

	if (action < 0) {
		fprintf(stderr, "missing action\n\n");
		rc = 2;
		goto out;
	}

	if (device != NULL && uid_given) {
		fprintf(stderr, "only one option, --device=DEVICEFILE or --user=UID expected\n\n");
		rc = 3;
		goto out;
	}

	if (uid_given) {
		switch (action) {
		case ACTION_ADD:
			/* Add ACL for given uid to all matching devices. */
			apply_acl_to_devices(uid, 1);
			break;
		case ACTION_REMOVE:
			remove_uid(uid, remove_session_id);
			break;
		case ACTION_CHANGE:
			remove_uid(uid, remove_session_id);
			apply_acl_to_devices(uid2, 1);
			break;
		case ACTION_NONE:
			goto out;
			break;
		default:
			g_assert_not_reached();
			break;
		}
	} else if (device != NULL) {
		/*
		 * Add ACLs for all current session uids to a given device.
		 *
		 * Or remove ACLs for uids which do not have any current local
		 * active session. Remove is not really interesting, because in
		 * most cases the device node is removed anyway.
		 */
		GSList *list;
		GSList *l;

		list = uids_with_local_active_session(NULL);
		for (l = list; l != NULL; l = g_slist_next(l)) {
			uid_t u;

			u = GPOINTER_TO_UINT(l->data);
			if (action == ACTION_ADD || !uid_in_list(list, u))
				set_facl(device, u, action == ACTION_ADD);
		}
		g_slist_free(list);
	} else {
		fprintf(stderr, "--device=DEVICEFILE or --user=UID expected\n\n");
		rc = 3;
	}
out:
	return rc;
}
Exemple #11
0
static void
windows_menu_image_notify (GimpDisplay      *display,
                           const GParamSpec *unused,
                           GimpUIManager    *manager)
{
  if (gimp_display_get_image (display))
    {
      gchar *merge_key = g_strdup_printf ("windows-display-%04d-merge-id",
                                          gimp_display_get_ID (display));
      guint  merge_id;

      merge_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (manager),
                                                      merge_key));

      if (! merge_id)
        {
          GtkWidget   *widget;
          const gchar *ui_path;
          gchar       *action_name;
          gchar       *action_path;
          gchar       *full_path;

          ui_path = g_object_get_data (G_OBJECT (manager),
                                       "image-menu-ui-path");

          action_name = gimp_display_get_action_name (display);
          action_path = g_strdup_printf ("%s/Windows/Images", ui_path);

          merge_id = gtk_ui_manager_new_merge_id (GTK_UI_MANAGER (manager));

          g_object_set_data (G_OBJECT (manager), merge_key,
                             GUINT_TO_POINTER (merge_id));

          gtk_ui_manager_add_ui (GTK_UI_MANAGER (manager), merge_id,
                                 action_path, action_name, action_name,
                                 GTK_UI_MANAGER_MENUITEM,
                                 FALSE);

          full_path = g_strconcat (action_path, "/", action_name, NULL);

          widget = gtk_ui_manager_get_widget (GTK_UI_MANAGER (manager),
                                              full_path);

          if (widget)
            {
              GtkAction *action;

              action = gimp_ui_manager_find_action (manager,
                                                    "windows", action_name);

              g_signal_connect_object (widget, "query-tooltip",
                                       G_CALLBACK (windows_menu_display_query_tooltip),
                                       action, 0);
            }

          g_free (action_name);
          g_free (action_path);
          g_free (full_path);
        }

      g_free (merge_key);
    }
  else
    {
      windows_menu_display_remove (manager->gimp->displays, display, manager);
    }
}
Exemple #12
0
/* XXX - "packet comment" is passed into dissector as data, but currently doesn't have a use */
static int
dissect_file_record(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
	proto_item  *volatile ti = NULL;
	guint	     cap_len = 0, frame_len = 0;
	proto_tree  *volatile fh_tree = NULL;
	proto_tree  *volatile tree;
	proto_item  *item;
	const gchar *cap_plurality, *frame_plurality;
	const color_filter_t *color_filter;
	file_data_t *file_data = (file_data_t*)data;

	tree=parent_tree;

	pinfo->current_proto = "File";

	/* if FILE is not referenced from any filters we don't need to worry about
	   generating any tree items.  */
	if(!proto_field_is_referenced(tree, proto_file)) {
		tree=NULL;
	} else {
		gboolean old_visible;

		/* Put in frame header information. */
		cap_len = tvb_captured_length(tvb);
		frame_len = tvb_reported_length(tvb);

		cap_plurality = plurality(cap_len, "", "s");
		frame_plurality = plurality(frame_len, "", "s");

		ti = proto_tree_add_protocol_format(tree, proto_file, tvb, 0, -1,
		    "File record %u: %u byte%s",
		    pinfo->fd->num, frame_len, frame_plurality);
		proto_item_append_text(ti, ", %u byte%s",
		    cap_len, cap_plurality);

		fh_tree = proto_item_add_subtree(ti, ett_file);

		proto_tree_add_int(fh_tree, hf_file_ftap_encap, tvb, 0, 0, pinfo->fd->lnk_t);

		proto_tree_add_uint(fh_tree, hf_file_record_number, tvb, 0, 0, pinfo->fd->num);

		proto_tree_add_uint_format(fh_tree, hf_file_record_len, tvb,
					   0, 0, frame_len, "Record Length: %u byte%s (%u bits)",
					   frame_len, frame_plurality, frame_len * 8);

		ti = proto_tree_add_boolean(fh_tree, hf_file_marked, tvb, 0, 0,pinfo->fd->flags.marked);
		PROTO_ITEM_SET_GENERATED(ti);

		ti = proto_tree_add_boolean(fh_tree, hf_file_ignored, tvb, 0, 0,pinfo->fd->flags.ignored);
		PROTO_ITEM_SET_GENERATED(ti);

		if(proto_field_is_referenced(tree, hf_file_protocols)) {
			/* we are going to be using proto_item_append_string() on
			 * hf_frame_protocols, and we must therefore disable the
			 * TRY_TO_FAKE_THIS_ITEM() optimisation for the tree by
			 * setting it as visible.
			 *
			 * See proto.h for details.
			 */
			old_visible = proto_tree_set_visible(fh_tree, TRUE);
			ti = proto_tree_add_string(fh_tree, hf_file_protocols, tvb, 0, 0, "");
			PROTO_ITEM_SET_GENERATED(ti);
			proto_tree_set_visible(fh_tree, old_visible);
		}

		if(pinfo->fd->pfd != 0){
			proto_item *ppd_item;
			guint num_entries = g_slist_length(pinfo->fd->pfd);
			guint i;
			ppd_item = proto_tree_add_uint(fh_tree, hf_file_num_p_prot_data, tvb, 0, 0, num_entries);
			PROTO_ITEM_SET_GENERATED(ppd_item);
			for(i=0; i<num_entries; i++){
				gchar* str = p_get_proto_name_and_key(wmem_file_scope(), pinfo, i);
				proto_tree_add_string_format(fh_tree, hf_file_proto_name_and_key, tvb, 0, 0, str, "%s", str);
			}
		}

#if 0
		if (show_file_off) {
			proto_tree_add_int64_format_value(fh_tree, hf_frame_file_off, tvb,
						    0, 0, pinfo->fd->file_off,
						    "%" G_GINT64_MODIFIER "d (0x%" G_GINT64_MODIFIER "x)",
						    pinfo->fd->file_off, pinfo->fd->file_off);
		}
#endif
	}

	if (pinfo->fd->flags.ignored) {
		/* Ignored package, stop handling here */
		col_set_str(pinfo->cinfo, COL_INFO, "<Ignored>");
		proto_tree_add_boolean_format(tree, hf_file_ignored, tvb, 0, -1, TRUE, "This record is marked as ignored");
		return tvb_captured_length(tvb);
	}

	/* Portable Exception Handling to trap Wireshark specific exceptions like BoundsError exceptions */
	TRY {
#ifdef _MSC_VER
		/* Win32: Visual-C Structured Exception Handling (SEH) to trap hardware exceptions
		   like memory access violations.
		   (a running debugger will be called before the except part below) */
		/* Note: A Windows "exceptional exception" may leave the kazlib's (Portable Exception Handling)
		   stack in an inconsistent state thus causing a crash at some point in the
		   handling of the exception.
		   See: https://www.wireshark.org/lists/wireshark-dev/200704/msg00243.html
		*/
		__try {
#endif
			if (!dissector_try_uint(file_encap_dissector_table, pinfo->fd->lnk_t,
						tvb, pinfo, parent_tree)) {

				col_set_str(pinfo->cinfo, COL_PROTOCOL, "UNKNOWN");
				col_add_fstr(pinfo->cinfo, COL_INFO, "FTAP_ENCAP = %d",
					     pinfo->fd->lnk_t);
				call_dissector(data_handle,tvb, pinfo, parent_tree);
			}
#ifdef _MSC_VER
		} __except(EXCEPTION_EXECUTE_HANDLER /* handle all exceptions */) {
			switch(GetExceptionCode()) {
			case(STATUS_ACCESS_VIOLATION):
				show_exception(tvb, pinfo, parent_tree, DissectorError,
					       "STATUS_ACCESS_VIOLATION: dissector accessed an invalid memory address");
				break;
			case(STATUS_INTEGER_DIVIDE_BY_ZERO):
				show_exception(tvb, pinfo, parent_tree, DissectorError,
					       "STATUS_INTEGER_DIVIDE_BY_ZERO: dissector tried an integer division by zero");
				break;
			case(STATUS_STACK_OVERFLOW):
				show_exception(tvb, pinfo, parent_tree, DissectorError,
					       "STATUS_STACK_OVERFLOW: dissector overflowed the stack (e.g. endless loop)");
				/* XXX - this will have probably corrupted the stack,
				   which makes problems later in the exception code */
				break;
				/* XXX - add other hardware exception codes as required */
			default:
				show_exception(tvb, pinfo, parent_tree, DissectorError,
					       g_strdup_printf("dissector caused an unknown exception: 0x%x", GetExceptionCode()));
			}
		}
#endif
	}
	CATCH_BOUNDS_AND_DISSECTOR_ERRORS {
		show_exception(tvb, pinfo, parent_tree, EXCEPT_CODE, GET_MESSAGE);
	}
	ENDTRY;

	if(proto_field_is_referenced(tree, hf_file_protocols)) {
		wmem_strbuf_t *val = wmem_strbuf_new(wmem_packet_scope(), "");
		wmem_list_frame_t *frame;
		/* skip the first entry, it's always the "frame" protocol */
		frame = wmem_list_frame_next(wmem_list_head(pinfo->layers));
		if (frame) {
			wmem_strbuf_append(val, proto_get_protocol_filter_name(GPOINTER_TO_UINT(wmem_list_frame_data(frame))));
			frame = wmem_list_frame_next(frame);
		}
		while (frame) {
			wmem_strbuf_append_c(val, ':');
			wmem_strbuf_append(val, proto_get_protocol_filter_name(GPOINTER_TO_UINT(wmem_list_frame_data(frame))));
			frame = wmem_list_frame_next(frame);
		}
		proto_item_append_string(ti, wmem_strbuf_get_str(val));
	}

	/*  Call postdissectors if we have any (while trying to avoid another
	 *  TRY/CATCH)
	 */
	if (have_postdissector()) {
		TRY {
#ifdef _MSC_VER
			/* Win32: Visual-C Structured Exception Handling (SEH)
			   to trap hardware exceptions like memory access violations */
			/* (a running debugger will be called before the except part below) */
			/* Note: A Windows "exceptional exception" may leave the kazlib's (Portable Exception Handling)
			   stack in an inconsistent state thus causing a crash at some point in the
			   handling of the exception.
			   See: https://www.wireshark.org/lists/wireshark-dev/200704/msg00243.html
			*/
			__try {
#endif
				call_all_postdissectors(tvb, pinfo, parent_tree);
#ifdef _MSC_VER
			} __except(EXCEPTION_EXECUTE_HANDLER /* handle all exceptions */) {
				switch(GetExceptionCode()) {
				case(STATUS_ACCESS_VIOLATION):
					show_exception(tvb, pinfo, parent_tree, DissectorError,
						       "STATUS_ACCESS_VIOLATION: dissector accessed an invalid memory address");
					break;
				case(STATUS_INTEGER_DIVIDE_BY_ZERO):
					show_exception(tvb, pinfo, parent_tree, DissectorError,
						       "STATUS_INTEGER_DIVIDE_BY_ZERO: dissector tried an integer division by zero");
					break;
				case(STATUS_STACK_OVERFLOW):
					show_exception(tvb, pinfo, parent_tree, DissectorError,
						       "STATUS_STACK_OVERFLOW: dissector overflowed the stack (e.g. endless loop)");
					/* XXX - this will have probably corrupted the stack,
					   which makes problems later in the exception code */
					break;
					/* XXX - add other hardware exception codes as required */
				default:
					show_exception(tvb, pinfo, parent_tree, DissectorError,
						       g_strdup_printf("dissector caused an unknown exception: 0x%x", GetExceptionCode()));
				}
			}
#endif
		}
		CATCH_BOUNDS_AND_DISSECTOR_ERRORS {
			show_exception(tvb, pinfo, parent_tree, EXCEPT_CODE, GET_MESSAGE);
		}
		ENDTRY;
	}

	/* XXX optimize this so it doesn't need to scan the second time */
	color_filter = color_filters_colorize_packet(file_data->color_edt);

	if (color_filter) {
		pinfo->fd->color_filter = color_filter;
		item = proto_tree_add_string(fh_tree, hf_file_color_filter_name, tvb,
					     0, 0, color_filter->filter_name);
		PROTO_ITEM_SET_GENERATED(item);
		item = proto_tree_add_string(fh_tree, hf_file_color_filter_text, tvb,
					     0, 0, color_filter->filter_text);
		PROTO_ITEM_SET_GENERATED(item);
	}

	tap_queue_packet(file_tap, pinfo, NULL);


	if (pinfo->frame_end_routines) {
		g_slist_foreach(pinfo->frame_end_routines, &call_file_record_end_routine, NULL);
		g_slist_free(pinfo->frame_end_routines);
		pinfo->frame_end_routines = NULL;
	}

	return tvb_captured_length(tvb);
}
Exemple #13
0
/**
 * Enqueues a kernel for execution on a device.
 *
 * Internally, this function calls the clSetKernelArg() OpenCL function
 * for each argument defined with the ::ccl_kernel_set_arg() function,
 * and the executes the kernel using the clEnqueueNDRangeKernel() OpenCL
 * function.
 *
 * @warning This function is not thread-safe. For multi-threaded
 * access to the same kernel function, create multiple instances of
 * a kernel wrapper for the given kernel function with
 * ::ccl_kernel_new(), one for each thread.
 *
 * @public @memberof ccl_kernel
 *
 * @param[in] krnl A kernel wrapper object.
 * @param[in] cq A command queue wrapper object.
 * @param[in] work_dim The number of dimensions used to specify the
 * global work-items and work-items in the work-group.
 * @param[in] global_work_offset Can be used to specify an array of
 * `work_dim` unsigned values that describe the offset used to calculate
 * the global ID of a work-item.
 * @param[in] global_work_size An array of `work_dim` unsigned values
 * that describe the number of global work-items in `work_dim`
 * dimensions that will execute the kernel function.
 * @param[in] local_work_size An array of `work_dim` unsigned values
 * that describe the number of work-items that make up a work-group that
 * will execute the specified kernel.
 * @param[in,out] evt_wait_lst List of events that need to complete
 * before this command can be executed. The list will be cleared and
 * can be reused by client code.
 * @param[out] err Return location for a ::CCLErr object, or `NULL` if error
 * reporting is to be ignored.
 * @return Event wrapper object that identifies this command.
 * */
CCL_EXPORT
CCLEvent* ccl_kernel_enqueue_ndrange(CCLKernel* krnl, CCLQueue* cq,
	cl_uint work_dim, const size_t* global_work_offset,
	const size_t* global_work_size, const size_t* local_work_size,
	CCLEventWaitList* evt_wait_lst, CCLErr** err) {

	/* Make sure krnl is not NULL. */
	g_return_val_if_fail(krnl != NULL, NULL);
	/* Make sure cq is not NULL. */
	g_return_val_if_fail(cq != NULL, NULL);
	/* Make sure err is NULL or it is not set. */
	g_return_val_if_fail(err == NULL || *err == NULL, NULL);

	/* OpenCL status flag. */
	cl_int ocl_status;

	/* OpenCL event. */
	cl_event event;
	/* Event wrapper. */
	CCLEvent* evt;

	/* Iterator for table of kernel arguments. */
	GHashTableIter iter;
	gpointer arg_index_ptr, arg_ptr;

	/* Set pending kernel arguments. */
	if (krnl->args != NULL) {
		g_hash_table_iter_init(&iter, krnl->args);
		while (g_hash_table_iter_next(&iter, &arg_index_ptr, &arg_ptr)) {
			cl_uint arg_index = GPOINTER_TO_UINT(arg_index_ptr);
			CCLArg* arg = (CCLArg*) arg_ptr;
			ocl_status = clSetKernelArg(ccl_kernel_unwrap(krnl), arg_index,
				ccl_arg_size(arg), ccl_arg_value(arg));
			ccl_if_err_create_goto(*err, CCL_OCL_ERROR,
				CL_SUCCESS != ocl_status, ocl_status, error_handler,
				"%s: unable to set kernel arg %d (OpenCL error %d: %s).",
				CCL_STRD, arg_index, ocl_status, ccl_err(ocl_status));
			g_hash_table_iter_remove(&iter);
		}
	}

	/* Run kernel. */
	ocl_status = clEnqueueNDRangeKernel(ccl_queue_unwrap(cq),
		ccl_kernel_unwrap(krnl), work_dim, global_work_offset,
		global_work_size, local_work_size,
		ccl_event_wait_list_get_num_events(evt_wait_lst),
		ccl_event_wait_list_get_clevents(evt_wait_lst), &event);
	ccl_if_err_create_goto(*err, CCL_OCL_ERROR,
		CL_SUCCESS != ocl_status, ocl_status, error_handler,
		"%s: unable to enqueue kernel (OpenCL error %d: %s).",
		CCL_STRD, ocl_status, ccl_err(ocl_status));

	/* Wrap event and associate it with the respective command queue.
	 * The event object will be released automatically when the command
	 * queue is released. */
	evt = ccl_queue_produce_event(cq, event);

	/* Clear event wait list. */
	ccl_event_wait_list_clear(evt_wait_lst);

	/* If we got here, everything is OK. */
	g_assert(err == NULL || *err == NULL);
	goto finish;

error_handler:

	/* If we got here there was an error, verify that it is so. */
	g_assert(err == NULL || *err != NULL);

	/* An error occurred, return NULL to signal it. */
	evt = NULL;

finish:

	/* Return evt. */
	return evt;

}
static void
test_seek_FORMAT_TIME_by_sample (const gchar * fn, GList * seek_positions)
{
  GstElement *pipeline, *src, *sink;
  GstAdapter *adapter;
  GstSample *sample;
  GstCaps *caps;
  gconstpointer answer;
  guint answer_size;

  pipeline = gst_parse_launch ("filesrc name=src ! decodebin ! "
      "audioconvert dithering=0 ! appsink name=sink", NULL);

  src = gst_bin_get_by_name (GST_BIN (pipeline), "src");
  g_object_set (src, "location", fn, NULL);
  gst_object_unref (src);

  sink = gst_bin_get_by_name (GST_BIN (pipeline), "sink");
  caps = gst_caps_new_simple ("audio/x-raw",
      "format", G_TYPE_STRING, GST_AUDIO_NE (S16),
      "rate", G_TYPE_INT, SAMPLE_FREQ, "channels", G_TYPE_INT, 2, NULL);
  g_object_set (sink, "caps", caps, "sync", FALSE, NULL);
  gst_caps_unref (caps);

  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* wait for preroll, so we can seek */
  gst_bus_timed_pop_filtered (GST_ELEMENT_BUS (pipeline), GST_CLOCK_TIME_NONE,
      GST_MESSAGE_ASYNC_DONE);

  /* first, read entire file to end */
  adapter = gst_adapter_new ();
  while ((sample = gst_app_sink_pull_sample (GST_APP_SINK (sink)))) {
    gst_adapter_push (adapter, gst_buffer_ref (gst_sample_get_buffer (sample)));
    gst_sample_unref (sample);
  }
  answer_size = gst_adapter_available (adapter);
  answer = gst_adapter_map (adapter, answer_size);
  /* g_print ("%s: read %u bytes\n", fn, answer_size); */

  g_print ("%10s\t%10s\t%10s\n", "requested", "sample per ts", "actual(data)");

  while (seek_positions != NULL) {
    gconstpointer found;
    GstMapInfo map;
    GstBuffer *buf;
    gboolean ret;
    guint actual_position, buffer_timestamp_position;
    guint seek_sample;

    seek_sample = GPOINTER_TO_UINT (seek_positions->data);

    ret = gst_element_seek_simple (pipeline, GST_FORMAT_TIME,
        GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE,
        sample_to_nanotime (seek_sample));

    g_assert (ret);

    sample = gst_app_sink_pull_sample (GST_APP_SINK (sink));

    buf = gst_sample_get_buffer (sample);
    gst_buffer_map (buf, &map, GST_MAP_READ);
    found = memmem (answer, answer_size, map.data, map.size);
    gst_buffer_unmap (buf, &map);

    g_assert (found != NULL);
    actual_position = ((goffset) ((guint8 *) found - (guint8 *) answer)) / 4;
    buffer_timestamp_position = nanotime_to_sample (GST_BUFFER_PTS (buf));
    g_print ("%10u\t%10u\t%10u\n", seek_sample, buffer_timestamp_position,
        actual_position);
    gst_sample_unref (sample);

    seek_positions = seek_positions->next;
  }

  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (sink);
  gst_object_unref (pipeline);
  g_object_unref (adapter);
}
void
add_hostlist_table_data(conv_hash_t *ch, const address *addr, guint32 port, gboolean sender, int num_frames, int num_bytes, hostlist_dissector_info_t *host_info, port_type port_type_val)
{
    hostlist_talker_t *talker=NULL;
    int talker_idx=0;

    /* XXX should be optimized to allocate n extra entries at a time
       instead of just one */
    /* if we don't have any entries at all yet */
    if(ch->conv_array==NULL){
        ch->conv_array=g_array_sized_new(FALSE, FALSE, sizeof(hostlist_talker_t), 10000);
        ch->hashtable = g_hash_table_new_full(host_hash,
                                              host_match, /* key_equal_func */
                                              g_free,     /* key_destroy_func */
                                              NULL);      /* value_destroy_func */
    }
    else {
        /* try to find it among the existing known conversations */
        host_key_t existing_key;
        gpointer talker_idx_hash_val;

        copy_address_shallow(&existing_key.myaddress, addr);
        existing_key.port = port;

        if (g_hash_table_lookup_extended(ch->hashtable, &existing_key, NULL, &talker_idx_hash_val)) {
            talker = &g_array_index(ch->conv_array, hostlist_talker_t, GPOINTER_TO_UINT(talker_idx_hash_val));
        }
    }

    /* if we still don't know what talker this is it has to be a new one
       and we have to allocate it and append it to the end of the list */
    if(talker==NULL){
        host_key_t *new_key;
        hostlist_talker_t host;

        copy_address(&host.myaddress, addr);
        host.dissector_info = host_info;
        host.ptype=port_type_val;
        host.port=port;
        host.rx_frames=0;
        host.tx_frames=0;
        host.rx_bytes=0;
        host.tx_bytes=0;
        host.modified = TRUE;

        g_array_append_val(ch->conv_array, host);
        talker_idx= ch->conv_array->len - 1;
        talker=&g_array_index(ch->conv_array, hostlist_talker_t, talker_idx);

        /* hl->hosts address is not a constant but address.data is */
        new_key = g_new(host_key_t,1);
        set_address(&new_key->myaddress, talker->myaddress.type, talker->myaddress.len, talker->myaddress.data);
        new_key->port = port;
        g_hash_table_insert(ch->hashtable, new_key, GUINT_TO_POINTER(talker_idx));
    }

    /* if this is a new talker we need to initialize the struct */
    talker->modified = TRUE;

    /* update the talker struct */
    if( sender ){
        talker->tx_frames+=num_frames;
        talker->tx_bytes+=num_bytes;
    } else {
        talker->rx_frames+=num_frames;
        talker->rx_bytes+=num_bytes;
    }
}
Exemple #16
0
static gboolean
test_type_is_a (GType type, gpointer is_a_type)
{
  return g_type_is_a (type, (GType) GPOINTER_TO_UINT (is_a_type));
}
Exemple #17
0
static void
selection_handler( GtkWidget *WXUNUSED(widget),
                   GtkSelectionData *selection_data,
                   guint WXUNUSED(info),
                   guint WXUNUSED(time),
                   gpointer signal_data )
{
    wxClipboard * const clipboard = wxTheClipboard;
    if ( !clipboard )
        return;

    wxDataObject * const data = clipboard->GTKGetDataObject(
        gtk_selection_data_get_selection(selection_data));
    if ( !data )
        return;

    // ICCCM says that TIMESTAMP is a required atom.
    // In particular, it satisfies Klipper, which polls
    // TIMESTAMP to see if the clipboards content has changed.
    // It shall return the time which was used to set the data.
    if (gtk_selection_data_get_target(selection_data) == g_timestampAtom)
    {
        guint timestamp = GPOINTER_TO_UINT (signal_data);
        gtk_selection_data_set(selection_data,
                               GDK_SELECTION_TYPE_INTEGER,
                               32,
                               (guchar*)&(timestamp),
                               sizeof(timestamp));
        wxLogTrace(TRACE_CLIPBOARD,
                   wxT("Clipboard TIMESTAMP requested, returning timestamp=%u"),
                   timestamp);
        return;
    }

    wxDataFormat format(gtk_selection_data_get_target(selection_data));

    wxLogTrace(TRACE_CLIPBOARD,
               wxT("clipboard data in format %s, GtkSelectionData is target=%s type=%s selection=%s timestamp=%u"),
               format.GetId().c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_target(selection_data)))).c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_data_type(selection_data)))).c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_selection(selection_data)))).c_str(),
               GPOINTER_TO_UINT( signal_data )
               );

    if ( !data->IsSupportedFormat( format ) )
        return;

    int size = data->GetDataSize( format );
    if ( !size )
        return;

    wxCharBuffer buf(size - 1); // it adds 1 internally (for NUL)

    // text data must be returned in UTF8 if format is wxDF_UNICODETEXT
    if ( !data->GetDataHere(format, buf.data()) )
        return;

    // use UTF8_STRING format if requested in Unicode build but just plain
    // STRING one in ANSI or if explicitly asked in Unicode
#if wxUSE_UNICODE
    if (format == wxDataFormat(wxDF_UNICODETEXT))
    {
        gtk_selection_data_set_text(
            selection_data,
            (const gchar*)buf.data(),
            size );
    }
    else
#endif // wxUSE_UNICODE
    {
        gtk_selection_data_set(
            selection_data,
            format.GetFormatId(),
            8*sizeof(gchar),
            (const guchar*)buf.data(),
            size );
    }
}
Exemple #18
0
static void
afsocket_sd_close_fd(gpointer value)
{
  gint fd = GPOINTER_TO_UINT(value) - 1;
  close(fd);
}
Exemple #19
0
static void on_cell_renderer_pixbuf_destroy(gpointer user_data, GObject* render)
{
    g_signal_handler_disconnect(fm_config, GPOINTER_TO_UINT(user_data));
}
Exemple #20
0
/* 
 * actually, we might want to queue the finalize requests in a separate thread,
 * but we need to be careful about the execution domain of the thread...
 */
void
mono_gc_run_finalize (void *obj, void *data)
{
	MonoObject *exc = NULL;
	MonoObject *o;
#ifndef HAVE_SGEN_GC
	MonoObject *o2;
#endif
	MonoMethod* finalizer = NULL;
	MonoDomain *caller_domain = mono_domain_get ();
	MonoDomain *domain;
	RuntimeInvokeFunction runtime_invoke;

	o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));

	if (suspend_finalizers)
		return;

	domain = o->vtable->domain;

#ifndef HAVE_SGEN_GC
	mono_domain_finalizers_lock (domain);

	o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);

	mono_domain_finalizers_unlock (domain);

	if (!o2)
		/* Already finalized somehow */
		return;
#endif

	/* make sure the finalizer is not called again if the object is resurrected */
	object_register_finalizer (obj, NULL);

	if (o->vtable->klass == mono_defaults.internal_thread_class) {
		MonoInternalThread *t = (MonoInternalThread*)o;

		if (mono_gc_is_finalizer_internal_thread (t))
			/* Avoid finalizing ourselves */
			return;

		if (t->threadpool_thread && finalizing_root_domain) {
			/* Don't finalize threadpool threads when
			   shutting down - they're finalized when the
			   threadpool shuts down. */
			add_thread_to_finalize (t);
			return;
		}
	}

	if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
		/*
		 * These can't be finalized during unloading/shutdown, since that would
		 * free the native code which can still be referenced by other
		 * finalizers.
		 * FIXME: This is not perfect, objects dying at the same time as 
		 * dynamic methods can still reference them even when !shutdown.
		 */
		return;
	}

	if (mono_runtime_get_no_exec ())
		return;

	/* speedup later... and use a timeout */
	/* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */

	/* Use _internal here, since this thread can enter a doomed appdomain */
	mono_domain_set_internal (mono_object_domain (o));

	/* delegates that have a native function pointer allocated are
	 * registered for finalization, but they don't have a Finalize
	 * method, because in most cases it's not needed and it's just a waste.
	 */
	if (o->vtable->klass->delegate) {
		MonoDelegate* del = (MonoDelegate*)o;
		if (del->delegate_trampoline)
			mono_delegate_free_ftnptr ((MonoDelegate*)o);
		mono_domain_set_internal (caller_domain);
		return;
	}

	finalizer = mono_class_get_finalizer (o->vtable->klass);

#ifndef DISABLE_COM
	/* If object has a CCW but has no finalizer, it was only
	 * registered for finalization in order to free the CCW.
	 * Else it needs the regular finalizer run.
	 * FIXME: what to do about ressurection and suppression
	 * of finalizer on object with CCW.
	 */
	if (mono_marshal_free_ccw (o) && !finalizer) {
		mono_domain_set_internal (caller_domain);
		return;
	}
#endif

	/* 
	 * To avoid the locking plus the other overhead of mono_runtime_invoke (),
	 * create and precompile a wrapper which calls the finalize method using
	 * a CALLVIRT.
	 */
	if (!domain->finalize_runtime_invoke) {
		MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);

		domain->finalize_runtime_invoke = mono_compile_method (invoke);
	}

	runtime_invoke = domain->finalize_runtime_invoke;

	mono_runtime_class_init (o->vtable);

	if (G_UNLIKELY (MONO_GC_FINALIZE_INVOKE_ENABLED ())) {
		MONO_GC_FINALIZE_INVOKE ((unsigned long)o, mono_object_get_size (o),
				o->vtable->klass->name_space, o->vtable->klass->name);
	}

	runtime_invoke (o, NULL, &exc, NULL);

	if (exc)
		mono_internal_thread_unhandled_exception (exc);

	mono_domain_set_internal (caller_domain);
}
Exemple #21
0
char *
gui_get_image_save_info (GtkWindow *toplevel, GSList *supported_formats,
			 GOImageFormat *ret_format, double *resolution)
{
	GOImageFormat format;
	GOImageFormatInfo const *format_info;
	GtkComboBox *format_combo = NULL;
	GtkFileChooser *fsel = gui_image_chooser_new (TRUE);
	GtkWidget *expander = NULL;
	GtkWidget *resolution_spin = NULL;
	GtkWidget *resolution_table;
	GladeXML *gui;
	SaveInfoState *state;
	const char *key = "gui_get_image_save_info";
	char *uri = NULL;

	state = g_object_get_data (G_OBJECT (toplevel), key);
	if (state == NULL) {
		state = g_new (SaveInfoState, 1);
		g_return_val_if_fail (state != NULL, NULL);
		state->uri = NULL;
		state->resolution = 150.0;
		state->is_expanded = FALSE;
		state->format = GO_IMAGE_FORMAT_SVG;
		g_object_set_data_full (G_OBJECT (toplevel), key,
					state, (GDestroyNotify) save_info_state_free);
	}

	g_object_set (G_OBJECT (fsel), "title", _("Save as"), NULL);

	gui = go_libglade_new ("go-image-save-dialog-extra.glade", 
			       "image_save_dialog_extra", 
			       GETTEXT_PACKAGE, NULL);
	if (gui != NULL) {
		GtkWidget *widget;

		/* Format selection UI */
		if (supported_formats != NULL && ret_format != NULL) {
			int i;
			GSList *l;
			format_combo = GTK_COMBO_BOX (glade_xml_get_widget (gui, "format_combo"));
			for (l = supported_formats, i = 0; l != NULL; l = l->next, i++) {
				format = GPOINTER_TO_UINT (l->data);
				format_info = go_image_get_format_info (format);
				gtk_combo_box_append_text (format_combo, _(format_info->desc)); 
				if (format == state->format) 
					gtk_combo_box_set_active (format_combo, i);
			}
			if (gtk_combo_box_get_active (format_combo) < 0)
				gtk_combo_box_set_active (format_combo, 0);
		} else {
			widget = glade_xml_get_widget (gui, "file_type_box");
			gtk_widget_hide (widget);
		}

		/* Export setting expander */
		expander = glade_xml_get_widget (gui, "export_expander");
		if (resolution != NULL) {
			gtk_expander_set_expanded (GTK_EXPANDER (expander), state->is_expanded);
			resolution_spin = glade_xml_get_widget (gui, "resolution_spin");
			gtk_spin_button_set_value (GTK_SPIN_BUTTON (resolution_spin), state->resolution);
		} else 
			gtk_widget_hide (expander);

		if (resolution != NULL && supported_formats != NULL && ret_format != NULL) {
			widget = glade_xml_get_widget (gui, "image_save_dialog_extra");
			gtk_file_chooser_set_extra_widget (fsel, widget);

			resolution_table = glade_xml_get_widget (gui, "resolution_table");
		
			cb_format_combo_changed (format_combo, resolution_table);	
			g_signal_connect (GTK_WIDGET (format_combo), "changed", 
					  G_CALLBACK (cb_format_combo_changed), resolution_table);
		}

		g_object_unref (G_OBJECT (gui));
	}

	if (state->uri != NULL) {
		gtk_file_chooser_set_uri (fsel, state->uri);
		gtk_file_chooser_unselect_all (fsel);
	}
	
	/* Show file selector */
 loop:
	if (!go_gtk_file_sel_dialog (toplevel, GTK_WIDGET (fsel)))
		goto out;
	uri = gtk_file_chooser_get_uri (fsel);
	if (format_combo) {
		char *new_uri = NULL;

		format = GPOINTER_TO_UINT (g_slist_nth_data 
			(supported_formats, 
			 gtk_combo_box_get_active (format_combo)));
		format_info = go_image_get_format_info (format);
		if (!go_url_check_extension (uri, format_info->ext, &new_uri) &&
		    !go_gtk_query_yes_no (GTK_WINDOW (fsel), TRUE,
		     _("The given file extension does not match the"
		       " chosen file type. Do you want to use this name"
		       " anyway?"))) {
			g_free (new_uri);
			g_free (uri);
			uri = NULL;
			goto out;
		} else {
			g_free (uri);
			uri = new_uri;
		}
		*ret_format = format;
	}
	if (!go_gtk_url_is_writeable (GTK_WINDOW (fsel), uri, TRUE)) {
		g_free (uri);
		uri = NULL;
		goto loop;
	}
 out:
	if (uri != NULL) {
		g_free (state->uri);
		state->uri = g_strdup (uri);
		state->format = *ret_format;
		if (resolution != NULL) {
			state->is_expanded = gtk_expander_get_expanded (GTK_EXPANDER (expander));
			*resolution =  gtk_spin_button_get_value (GTK_SPIN_BUTTON (resolution_spin));
			state->resolution = *resolution;
		}
	}

	gtk_widget_destroy (GTK_WIDGET (fsel));

	return uri;
}
Exemple #22
0
sc_result sc_storage_element_free(sc_addr addr)
{
    sc_element *el, *el2;
    sc_addr _addr;
    sc_uint addr_int;

    GSList *remove_list = 0;

    el = el2 = 0;

    if (sc_storage_is_element(addr) == SC_FALSE)
        return SC_RESULT_ERROR;

    if (sc_iterator_has_any_timestamp())
        storage_time_stamp++;

    remove_list = g_slist_append(remove_list, GUINT_TO_POINTER(SC_ADDR_LOCAL_TO_INT(addr)));

    while (remove_list != 0)
    {
        // get sc-addr for removing
        addr_int = GPOINTER_TO_UINT(remove_list->data);
        _addr.seg = SC_ADDR_LOCAL_SEG_FROM_INT(addr_int);
        _addr.offset = SC_ADDR_LOCAL_OFFSET_FROM_INT(addr_int);

        // go to next sc-addr in list
        remove_list = g_slist_delete_link(remove_list, remove_list);

        el = sc_storage_get_element(_addr, SC_TRUE);
        g_assert(el != 0 && el->type != 0);

        // remove registered events before deletion
        sc_event_notify_element_deleted(_addr);

        el->delete_time_stamp = storage_time_stamp;

        if (el->type & sc_type_arc_mask)
        {
            sc_event_emit(el->arc.begin, SC_EVENT_REMOVE_OUTPUT_ARC, _addr);
            sc_event_emit(el->arc.end, SC_EVENT_REMOVE_INPUT_ARC, _addr);
        }

        // Iterate all connectors for deleted element and append them into remove_list
        _addr = el->first_out_arc;
        while (SC_ADDR_IS_NOT_EMPTY(_addr))
        {
            el2 = sc_storage_get_element(_addr, SC_TRUE);

            // do not append elements, that have delete_time_stamp != 0
            if (el2->delete_time_stamp == 0)
                remove_list = g_slist_append(remove_list, GUINT_TO_POINTER(SC_ADDR_LOCAL_TO_INT(_addr)));

            _addr = el2->arc.next_out_arc;
        }

        _addr = el->first_in_arc;
        while (SC_ADDR_IS_NOT_EMPTY(_addr))
        {
            el2 = sc_storage_get_element(_addr, SC_TRUE);

            // do not append elements, that have delete_time_stamp != 0
            if (el2->delete_time_stamp == 0)
                remove_list = g_slist_append(remove_list, GUINT_TO_POINTER(SC_ADDR_LOCAL_TO_INT(_addr)));


            _addr = el2->arc.next_in_arc;
        }

        // clean temp addr
        SC_ADDR_MAKE_EMPTY(_addr);
    }

    return SC_RESULT_OK;
}
Exemple #23
0
  
  return closure;
}

static void
g_type_class_meta_marshal (GClosure       *closure,
			   GValue /*out*/ *return_value,
			   guint           n_param_values,
			   const GValue   *param_values,
			   gpointer        invocation_hint,
			   gpointer        marshal_data)
{
  GTypeClass *class;
  gpointer callback;
  /* GType itype = (GType) closure->data; */
  guint offset = GPOINTER_TO_UINT (marshal_data);
  
  class = G_TYPE_INSTANCE_GET_CLASS (g_value_peek_pointer (param_values + 0), itype, GTypeClass);
  callback = G_STRUCT_MEMBER (gpointer, class, offset);
  if (callback)
    closure->marshal (closure,
		      return_value,
		      n_param_values, param_values,
		      invocation_hint,
		      callback);
}

static void
g_type_iface_meta_marshal (GClosure       *closure,
			   GValue /*out*/ *return_value,
			   guint           n_param_values,
/**
 * get_throw_trampoline:
 *
 * Returns a function pointer which can be used to raise 
 * exceptions. The returned function has the following 
 * signature: void (*func) (MonoException *exc); or
 * void (*func) (guint32 ex_token, guint8* ip);
 *
 */
static gpointer 
get_throw_trampoline (int size, gboolean corlib, gboolean rethrow, gboolean llvm, gboolean resume_unwind, const char *tramp_name, MonoTrampInfo **info, gboolean aot)
{
	guint8 *start;
	guint8 *code;
	MonoJumpInfo *ji = NULL;
	GSList *unwind_ops = NULL;

	code = start = mono_global_codeman_reserve (size);

	mono_add_unwind_op_def_cfa (unwind_ops, code, start, ARMREG_SP, 0);

	/* save all the regs on the stack */
	ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_SP);
	ARM_PUSH (code, MONO_ARM_REGSAVE_MASK);

	mono_add_unwind_op_def_cfa (unwind_ops, code, start, ARMREG_SP, 10 * 4);
	mono_add_unwind_op_offset (unwind_ops, code, start, ARMREG_LR, -4);

	/* call throw_exception (exc, ip, sp, int_regs, fp_regs) */
	/* caller sp */
	ARM_ADD_REG_IMM8 (code, ARMREG_R2, ARMREG_SP, 10 * 4); /* 10 saved regs */
	/* exc is already in place in r0 */
	if (corlib) {
		/* The caller ip is already in R1 */
		if (llvm)
			/* Negate the ip adjustment done in mono_arm_throw_exception */
			ARM_ADD_REG_IMM8 (code, ARMREG_R1, ARMREG_R1, 4);
	} else {
		ARM_MOV_REG_REG (code, ARMREG_R1, ARMREG_LR); /* caller ip */
	}
	/* FIXME: pointer to the saved fp regs */
	/*pos = alloc_size - sizeof (double) * MONO_SAVED_FREGS;
	ppc_addi (code, ppc_r7, ppc_sp, pos);*/
	/* pointer to the saved int regs */
	ARM_MOV_REG_REG (code, ARMREG_R3, ARMREG_SP); /* the pushed regs */
	/* we encode rethrow in the ip, so we avoid args on the stack */
	ARM_ORR_REG_IMM8 (code, ARMREG_R1, ARMREG_R1, rethrow);

	if (aot) {
		ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, corlib ? "mono_arm_throw_exception_by_token" : "mono_arm_throw_exception");
		ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
		ARM_B (code, 0);
		*(gpointer*)(gpointer)code = NULL;
		code += 4;
		ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
	} else {
		code = mono_arm_emit_load_imm (code, ARMREG_IP, GPOINTER_TO_UINT (resume_unwind ? (gpointer)mono_arm_resume_unwind : (corlib ? (gpointer)mono_arm_throw_exception_by_token : (gpointer)mono_arm_throw_exception)));
	}
	ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
	ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_IP);
	/* we should never reach this breakpoint */
	ARM_DBRK (code);
	g_assert ((code - start) < size);
	mono_arch_flush_icache (start, code - start);

	if (info)
		*info = mono_tramp_info_create (g_strdup_printf (tramp_name), start, code - start, ji, unwind_ops);

	return start;
}
Exemple #25
0
static void
eog_application_show_window (EogWindow *window, gpointer user_data)
{
	gtk_window_present_with_time (GTK_WINDOW (window),
				      GPOINTER_TO_UINT (user_data));
}
static guint find_by_id (gconstpointer a, gconstpointer b)
{
	return GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (a), "daap_id")) != GPOINTER_TO_UINT (b);
}
static void train_word_pair(HashofUnigram hash_of_unigram,
                            KMixtureModelSingleGram * single_gram,
                            phrase_token_t token2, guint32 count){
    KMixtureModelArrayItem array_item;

    bool exists = single_gram->get_array_item(token2, array_item);
    if ( exists ) {
        guint32 maximum_occurs_allowed = std_lite::max
            (g_maximum_occurs,
             (guint32)ceil(array_item.m_Mr * g_maximum_increase_rates));
        /* Exceeds the maximum occurs allowed of the word or phrase,
         * in a single document.
         */
        if ( count > maximum_occurs_allowed ){
            gpointer value = NULL;
            assert( g_hash_table_lookup_extended
                    (hash_of_unigram, GUINT_TO_POINTER(token2),
                     NULL, &value) );
            guint32 freq = GPOINTER_TO_UINT(value);
            freq -= count;
            if ( freq > 0 ) {
                g_hash_table_insert(hash_of_unigram, GUINT_TO_POINTER(token2),
                                    GUINT_TO_POINTER(freq));
            } else if ( freq == 0 ) {
                assert(g_hash_table_steal(hash_of_unigram,
                                          GUINT_TO_POINTER(token2)));
            } else {
                assert(false);
            }
            return;
        }
        array_item.m_WC += count;
        /* array_item.m_T += count; the same as m_WC. */
        array_item.m_N_n_0 ++;
        if ( 1 == count )
            array_item.m_n_1 ++;
        array_item.m_Mr = std_lite::max(array_item.m_Mr, count);
        assert(single_gram->set_array_item(token2, array_item));
    } else { /* item doesn't exist. */
        /* the same as above. */
        if ( count > g_maximum_occurs ){
            gpointer value = NULL;
            assert( g_hash_table_lookup_extended
                    (hash_of_unigram, GUINT_TO_POINTER(token2),
                     NULL, &value) );
            guint32 freq = GPOINTER_TO_UINT(value);
            freq -= count;
            if ( freq > 0 ) {
                g_hash_table_insert(hash_of_unigram, GUINT_TO_POINTER(token2),
                                    GUINT_TO_POINTER(freq));
            } else if ( freq == 0 ) {
                assert(g_hash_table_steal(hash_of_unigram,
                                          GUINT_TO_POINTER(token2)));
            } else {
                assert(false);
            }
            return;
        }
        memset(&array_item, 0, sizeof(KMixtureModelArrayItem));
        array_item.m_WC = count;
        /* array_item.m_T = count; the same as m_WC. */
        array_item.m_N_n_0 = 1;
        if ( 1 == count )
            array_item.m_n_1 = 1;
        array_item.m_Mr = count;
        assert(single_gram->insert_array_item(token2, array_item));
    }

    /* save delta in the array header. */
    KMixtureModelArrayHeader array_header;
    single_gram->get_array_header(array_header);
    array_header.m_WC += count;
    single_gram->set_array_header(array_header);
}
void
add_conversation_table_data_with_conv_id(
    conv_hash_t *ch,
    const address *src,
    const address *dst,
    guint32 src_port,
    guint32 dst_port,
    conv_id_t conv_id,
    int num_frames,
    int num_bytes,
    nstime_t *ts,
    nstime_t *abs_ts,
    ct_dissector_info_t *ct_info,
    port_type ptype)
{
    const address *addr1, *addr2;
    guint32 port1, port2;
    conv_item_t *conv_item = NULL;
    unsigned int conversation_idx = 0;

    if (src_port > dst_port) {
        addr1 = src;
        addr2 = dst;
        port1 = src_port;
        port2 = dst_port;
    } else if (src_port < dst_port) {
        addr2 = src;
        addr1 = dst;
        port2 = src_port;
        port1 = dst_port;
    } else if (cmp_address(src, dst) < 0) {
        addr1 = src;
        addr2 = dst;
        port1 = src_port;
        port2 = dst_port;
    } else {
        addr2 = src;
        addr1 = dst;
        port2 = src_port;
        port1 = dst_port;
    }

    /* if we don't have any entries at all yet */
    if (ch->conv_array == NULL) {
        ch->conv_array = g_array_sized_new(FALSE, FALSE, sizeof(conv_item_t), 10000);

        ch->hashtable = g_hash_table_new_full(conversation_hash,
                                              conversation_equal, /* key_equal_func */
                                              g_free,             /* key_destroy_func */
                                              NULL);              /* value_destroy_func */

    } else {
        /* try to find it among the existing known conversations */
        conv_key_t existing_key;
        gpointer conversation_idx_hash_val;

        existing_key.addr1 = *addr1;
        existing_key.addr2 = *addr2;
        existing_key.port1 = port1;
        existing_key.port2 = port2;
        existing_key.conv_id = conv_id;
        if (g_hash_table_lookup_extended(ch->hashtable, &existing_key, NULL, &conversation_idx_hash_val)) {
            conv_item = &g_array_index(ch->conv_array, conv_item_t, GPOINTER_TO_UINT(conversation_idx_hash_val));
        }
    }

    /* if we still don't know what conversation this is it has to be a new one
       and we have to allocate it and append it to the end of the list */
    if (conv_item == NULL) {
        conv_key_t *new_key;
        conv_item_t new_conv_item;

        copy_address(&new_conv_item.src_address, addr1);
        copy_address(&new_conv_item.dst_address, addr2);
        new_conv_item.dissector_info = ct_info;
        new_conv_item.ptype = ptype;
        new_conv_item.src_port = port1;
        new_conv_item.dst_port = port2;
        new_conv_item.conv_id = conv_id;
        new_conv_item.rx_frames = 0;
        new_conv_item.tx_frames = 0;
        new_conv_item.rx_bytes = 0;
        new_conv_item.tx_bytes = 0;
        new_conv_item.modified = TRUE;

        if (ts) {
            memcpy(&new_conv_item.start_time, ts, sizeof(new_conv_item.start_time));
            memcpy(&new_conv_item.stop_time, ts, sizeof(new_conv_item.stop_time));
            memcpy(&new_conv_item.start_abs_time, abs_ts, sizeof(new_conv_item.start_abs_time));
        } else {
            nstime_set_unset(&new_conv_item.start_abs_time);
            nstime_set_unset(&new_conv_item.start_time);
            nstime_set_unset(&new_conv_item.stop_time);
        }
        g_array_append_val(ch->conv_array, new_conv_item);
        conversation_idx = ch->conv_array->len - 1;
        conv_item = &g_array_index(ch->conv_array, conv_item_t, conversation_idx);

        /* ct->conversations address is not a constant but src/dst_address.data are */
        new_key = g_new(conv_key_t, 1);
        set_address(&new_key->addr1, conv_item->src_address.type, conv_item->src_address.len, conv_item->src_address.data);
        set_address(&new_key->addr2, conv_item->dst_address.type, conv_item->dst_address.len, conv_item->dst_address.data);
        new_key->port1 = port1;
        new_key->port2 = port2;
        new_key->conv_id = conv_id;
        g_hash_table_insert(ch->hashtable, new_key, GUINT_TO_POINTER(conversation_idx));
    }

    /* update the conversation struct */
    conv_item->modified = TRUE;
    if ( (!cmp_address(src, addr1)) && (!cmp_address(dst, addr2)) && (src_port==port1) && (dst_port==port2) ) {
        conv_item->tx_frames += num_frames;
        conv_item->tx_bytes += num_bytes;
    } else {
        conv_item->rx_frames += num_frames;
        conv_item->rx_bytes += num_bytes;
    }

    if (ts) {
        if (nstime_cmp(ts, &conv_item->stop_time) > 0) {
            memcpy(&conv_item->stop_time, ts, sizeof(conv_item->stop_time));
        } else if (nstime_cmp(ts, &conv_item->start_time) < 0) {
            memcpy(&conv_item->start_time, ts, sizeof(conv_item->start_time));
            memcpy(&conv_item->start_abs_time, abs_ts, sizeof(conv_item->start_abs_time));
        }
    }
}
bool read_document(PhraseLargeTable2 * phrase_table,
                   FacadePhraseIndex * phrase_index,
                   FILE * document,
                   HashofDocument hash_of_document,
                   HashofUnigram hash_of_unigram){

    char * linebuf = NULL;size_t size = 0;
    phrase_token_t last_token, cur_token = last_token = 0;

    while ( getline(&linebuf, &size, document) ){
        if ( feof(document) )
            break;

        if ( '\n' == linebuf[strlen(linebuf) - 1] ) {
            linebuf[strlen(linebuf) - 1] = '\0';
        }

        TAGLIB_PARSE_SEGMENTED_LINE(phrase_index, token, linebuf);

        last_token = cur_token;
        cur_token = token;

        /* skip null_token in second word. */
        if ( null_token == cur_token )
            continue;

        gpointer value = NULL;
        gboolean lookup_result = g_hash_table_lookup_extended
            (hash_of_unigram, GUINT_TO_POINTER(cur_token),
             NULL, &value);
        if ( !lookup_result ){
            g_hash_table_insert(hash_of_unigram, GUINT_TO_POINTER(cur_token),
                                GUINT_TO_POINTER(1));
        } else {
            guint32 freq = GPOINTER_TO_UINT(value);
            freq ++;
            g_hash_table_insert(hash_of_unigram, GUINT_TO_POINTER(cur_token),
                                GUINT_TO_POINTER(freq));
        }

        /* skip pi-gram training. */
        if ( null_token == last_token ){
            if ( !g_train_pi_gram )
                continue;
            last_token = sentence_start;
        }

        /* remember the (last_token, cur_token) word pair. */
        HashofSecondWord hash_of_second_word = NULL;
        lookup_result = g_hash_table_lookup_extended
            (hash_of_document, GUINT_TO_POINTER(last_token),
             NULL, &value);
        if ( !lookup_result ){
            hash_of_second_word = g_hash_table_new
                (g_direct_hash, g_direct_equal);
        } else {
            hash_of_second_word = (HashofSecondWord) value;
        }

        value = NULL;
        lookup_result = g_hash_table_lookup_extended
            (hash_of_second_word, GUINT_TO_POINTER(cur_token),
             NULL, &value);
        guint32 count = 0;
        if ( lookup_result ) {
            count = GPOINTER_TO_UINT(value);
        }
        count ++;
        g_hash_table_insert(hash_of_second_word,
                            GUINT_TO_POINTER(cur_token),
                            GUINT_TO_POINTER(count));
        g_hash_table_insert(hash_of_document,
                            GUINT_TO_POINTER(last_token),
                            hash_of_second_word);
    }

    free(linebuf);

    return true;
}
Exemple #30
0
/**
 * get_throw_trampoline:
 *
 * Returns a function pointer which can be used to raise 
 * exceptions. The returned function has the following 
 * signature: void (*func) (MonoException *exc); or
 * void (*func) (guint32 ex_token, guint8* ip);
 *
 */
static gpointer 
get_throw_trampoline (int size, gboolean corlib, gboolean rethrow, gboolean llvm, gboolean resume_unwind, const char *tramp_name, MonoTrampInfo **info, gboolean aot)
{
	guint8 *start;
	guint8 *code;
	MonoJumpInfo *ji = NULL;
	GSList *unwind_ops = NULL;
	int cfa_offset;

	code = start = mono_global_codeman_reserve (size);

	mono_add_unwind_op_def_cfa (unwind_ops, code, start, ARMREG_SP, 0);

	/* save all the regs on the stack */
	ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_SP);
	ARM_PUSH (code, MONO_ARM_REGSAVE_MASK);

	cfa_offset = MONO_ARM_NUM_SAVED_REGS * sizeof (mgreg_t);
	mono_add_unwind_op_def_cfa (unwind_ops, code, start, ARMREG_SP, cfa_offset);
	mono_add_unwind_op_offset (unwind_ops, code, start, ARMREG_LR, - sizeof (mgreg_t));

	/* Save fp regs */
	if (!mono_arch_is_soft_float ()) {
		ARM_SUB_REG_IMM8 (code, ARMREG_SP, ARMREG_SP, sizeof (double) * 16);
		cfa_offset += sizeof (double) * 16;
		mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, cfa_offset);
		ARM_FSTMD (code, ARM_VFP_D0, 16, ARMREG_SP);
	}

	/* Param area */
	ARM_SUB_REG_IMM8 (code, ARMREG_SP, ARMREG_SP, 8);
	cfa_offset += 8;
	mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, cfa_offset);

	/* call throw_exception (exc, ip, sp, int_regs, fp_regs) */
	/* caller sp */
	ARM_ADD_REG_IMM8 (code, ARMREG_R2, ARMREG_SP, cfa_offset);
	/* we encode rethrow in sp */
	if (rethrow) {
		g_assert (!resume_unwind);
		g_assert (!corlib);
		ARM_ORR_REG_IMM8 (code, ARMREG_R2, ARMREG_R2, rethrow);
	}
	/* exc is already in place in r0 */
	if (corlib) {
		/* The caller ip is already in R1 */
		if (llvm)
			/* Negate the ip adjustment done in mono_arm_throw_exception */
			ARM_ADD_REG_IMM8 (code, ARMREG_R1, ARMREG_R1, 4);
	} else {
		ARM_MOV_REG_REG (code, ARMREG_R1, ARMREG_LR); /* caller ip */
	}
	/* int regs */
	ARM_ADD_REG_IMM8 (code, ARMREG_R3, ARMREG_SP, (cfa_offset - (MONO_ARM_NUM_SAVED_REGS * sizeof (mgreg_t))));
	/* fp regs */
	ARM_ADD_REG_IMM8 (code, ARMREG_LR, ARMREG_SP, 8);
	ARM_STR_IMM (code, ARMREG_LR, ARMREG_SP, 0);

	if (aot) {
		const char *icall_name;

		if (resume_unwind)
			icall_name = "mono_arm_resume_unwind";
		else if (corlib)
			icall_name = "mono_arm_throw_exception_by_token";
		else
			icall_name = "mono_arm_throw_exception";

		ji = mono_patch_info_list_prepend (ji, code - start, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
		ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
		ARM_B (code, 0);
		*(gpointer*)(gpointer)code = NULL;
		code += 4;
		ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
	} else {
		code = mono_arm_emit_load_imm (code, ARMREG_IP, GPOINTER_TO_UINT (resume_unwind ? (gpointer)mono_arm_resume_unwind : (corlib ? (gpointer)mono_arm_throw_exception_by_token : (gpointer)mono_arm_throw_exception)));
	}
	ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
	ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_IP);
	/* we should never reach this breakpoint */
	ARM_DBRK (code);
	g_assert ((code - start) < size);
	mono_arch_flush_icache (start, code - start);

	if (info)
		*info = mono_tramp_info_create (tramp_name, start, code - start, ji, unwind_ops);

	return start;
}