Esempio n. 1
0
/* like soup_message_headers_get_ranges(), except it returns:
 *   SOUP_STATUS_OK if there is no Range or it should be ignored.
 *   SOUP_STATUS_PARTIAL_CONTENT if there is at least one satisfiable range.
 *   SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE if @check_satisfiable
 *     is %TRUE and the request is not satisfiable given @total_length.
 */
guint
soup_message_headers_get_ranges_internal (SoupMessageHeaders  *hdrs,
					  goffset              total_length,
					  gboolean             check_satisfiable,
					  SoupRange          **ranges,
					  int                 *length)
{
	const char *range = soup_message_headers_get_one (hdrs, "Range");
	GSList *range_list, *r;
	GArray *array;
	char *spec, *end;
	int i;
	guint status = SOUP_STATUS_OK;

	if (!range || strncmp (range, "bytes", 5) != 0)
		return status;

	range += 5;
	while (g_ascii_isspace (*range))
		range++;
	if (*range++ != '=')
		return status;
	while (g_ascii_isspace (*range))
		range++;

	range_list = soup_header_parse_list (range);
	if (!range_list)
		return status;

	array = g_array_new (FALSE, FALSE, sizeof (SoupRange));
	for (r = range_list; r; r = r->next) {
		SoupRange cur;

		spec = r->data;
		if (*spec == '-') {
			cur.start = g_ascii_strtoll (spec, &end, 10) + total_length;
			cur.end = total_length - 1;
		} else {
			cur.start = g_ascii_strtoull (spec, &end, 10);
			if (*end == '-')
				end++;
			if (*end) {
				cur.end = g_ascii_strtoull (end, &end, 10);
				if (cur.end < cur.start) {
					status = SOUP_STATUS_OK;
					break;
				}
			} else
				cur.end = total_length - 1;
		}
		if (*end) {
			status = SOUP_STATUS_OK;
			break;
		} else if (check_satisfiable && cur.start >= total_length) {
			if (status == SOUP_STATUS_OK)
				status = SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE;
			continue;
		}

		g_array_append_val (array, cur);
		status = SOUP_STATUS_PARTIAL_CONTENT;
	}
	soup_header_free_list (range_list);

	if (status != SOUP_STATUS_PARTIAL_CONTENT) {
		g_array_free (array, TRUE);
		return status;
	}

	if (total_length) {
		g_array_sort (array, sort_ranges);
		for (i = 1; i < array->len; i++) {
			SoupRange *cur = &((SoupRange *)array->data)[i];
			SoupRange *prev = &((SoupRange *)array->data)[i - 1];

			if (cur->start <= prev->end) {
				prev->end = MAX (prev->end, cur->end);
				g_array_remove_index (array, i);
			}
		}
	}

	*ranges = (SoupRange *)array->data;
	*length = array->len;

	g_array_free (array, FALSE);
	return SOUP_STATUS_PARTIAL_CONTENT;
}
Esempio n. 2
0
File: sdl.c Progetto: adurdin/fs-uae
static void fs_emu_monitor_init()
{
    static bool initialized = false;
    if (initialized) {
        return;
    }
    initialized = true;

    g_fs_emu_monitors = g_array_new(false, true, sizeof(FSEmuMonitor));

    int display_index = 0;
    while (true) {
        SDL_DisplayMode mode;
        int error = SDL_GetDesktopDisplayMode(display_index, &mode);
        if (error) {
            break;
        }

        FSEmuMonitor monitor;
        monitor.index = display_index;
        SDL_Rect rect;
        error = SDL_GetDisplayBounds(display_index, &rect);
        if (error) {
            fs_log("Error retrieving display bounds for display %d: %s\n",
                   display_index, SDL_GetError());
            monitor.rect.x = 0;
            monitor.rect.y = 0;
            monitor.rect.w = 1024;
            monitor.rect.h = 768;
            monitor.refresh_rate = 1;
        } else {
            monitor.rect.x = rect.x;
            monitor.rect.y = rect.y;
            monitor.rect.w = rect.w;
            monitor.rect.h = rect.h;
            monitor.refresh_rate = mode.refresh_rate;
        }
        fs_log("[DISPLAY] %d: %dx%d+%d+%d @%d\n", display_index,
               monitor.rect.w, monitor.rect.h, monitor.rect.x, monitor.rect.y,
               monitor.refresh_rate);
        g_array_append_val(g_fs_emu_monitors, monitor);
        display_index += 1;
    }
    g_fs_emu_monitor_count = display_index;

#if 0
    SDL_DisplayMode mode;
    int error = SDL_GetCurrentDisplayMode(display_index, &mode);
    if (error) {
        fs_log("SDL_GetCurrentDisplayMode failed\n");
        SDL_ShowSimpleMessageBox(
            SDL_MESSAGEBOX_ERROR, "Display Error",
            "SDL_GetCurrentDisplayMode failed.", NULL);
        exit(1);
    }
    g_fs_emu_monitor_count = SDL_GetNumVideoDisplays();

    if (g_fs_emu_monitor_count < 1) {
        fs_log("Error %d retrieving number of displays/monitors\n",
               g_fs_emu_monitor_count);
        g_fs_emu_monitor_count = 1;
    }
    if (g_fs_emu_monitor_count >  FS_EMU_MONITOR_MAX_COUNT) {
        fs_log("Limiting number of displays to %d\n",
                FS_EMU_MONITOR_MAX_COUNT);
        g_fs_emu_monitor_count =  FS_EMU_MONITOR_MAX_COUNT;
    }

    for (int i = 0; i < g_fs_emu_monitor_count; i++) {
        SDL_Rect rect;
        FSEmuMonitor monitor;
        int error = SDL_GetDisplayBounds(i, &rect);
        if (error) {
            fs_log("Error retrieving display bounds for display %d: %s\n",
                   i, SDL_GetError());
            /* Setting dummy values on error*/
            rect.x = 0;
            rect.y = 0;
            rect.w = 1024;
            rect.h = 768;
        }

        monitor.rect.x = rect.x;
        monitor.rect.y = rect.y;
        monitor.rect.w = rect.w;
        monitor.rect.h = rect.h;
        monitor.index = i;

        g_array_append_val(g_fs_emu_monitors, monitor);
    }
#endif

    g_array_sort(g_fs_emu_monitors, fs_emu_monitor_compare);
    for (int i = 0; i < g_fs_emu_monitor_count; i++) {
        g_array_index(g_fs_emu_monitors, FSEmuMonitor, i).index = i;
        /* Set physical position flags (left, m-left, m-right, right) */
        int flags = 0;
        for (int j = 0; j < 4; j++) {
            int pos = (g_fs_emu_monitor_count - 1.0) * j / 3.0 + 0.5;
            fs_log("Monitor - j %d pos %d\n", j, pos);
            if (pos == i) {
                flags |= (1 << j);
            }
        }
        fs_log("Monitor index %d flags %d\n", i, flags);
        g_array_index(g_fs_emu_monitors, FSEmuMonitor, i).flags = flags;
    }
}
Esempio n. 3
0
static void
ide_clang_service_parse_worker (GTask        *task,
                                gpointer      source_object,
                                gpointer      task_data,
                                GCancellable *cancellable)
{
  g_autoptr(IdeClangTranslationUnit) ret = NULL;
  g_autoptr(IdeHighlightIndex) index = NULL;
  g_autoptr(IdeFile) file_copy = NULL;
  IdeClangService *self = source_object;
  CXTranslationUnit tu = NULL;
  ParseRequest *request = task_data;
  IdeContext *context;
  const gchar * const *argv;
  GFile *gfile;
  gsize argc = 0;
  const gchar *detail_error = NULL;
  enum CXErrorCode code;
  GArray *ar = NULL;
  gsize i;

  g_assert (G_IS_TASK (task));
  g_assert (IDE_IS_CLANG_SERVICE (source_object));
  g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));
  g_assert (IDE_IS_FILE (request->file));

  file_copy = g_object_ref (request->file);

  ar = g_array_new (FALSE, FALSE, sizeof (struct CXUnsavedFile));
  g_array_set_clear_func (ar, clear_unsaved_file);

  for (i = 0; i < request->unsaved_files->len; i++)
    {
      IdeUnsavedFile *iuf = g_ptr_array_index (request->unsaved_files, i);
      struct CXUnsavedFile uf;
      GBytes *content;
      GFile *file;

      file = ide_unsaved_file_get_file (iuf);
      content = ide_unsaved_file_get_content (iuf);

      uf.Filename = g_file_get_path (file);
      uf.Contents = g_bytes_get_data (content, NULL);
      uf.Length = g_bytes_get_size (content);

      g_array_append_val (ar, uf);
    }

  argv = (const gchar * const *)request->command_line_args;
  argc = argv ? g_strv_length (request->command_line_args) : 0;

  EGG_COUNTER_INC (ParseAttempts);
  code = clang_parseTranslationUnit2 (request->index,
                                      request->source_filename,
                                      argv, argc,
                                      (struct CXUnsavedFile *)(void *)ar->data,
                                      ar->len,
                                      request->options,
                                      &tu);

  switch (code)
    {
    case CXError_Success:
      index = ide_clang_service_build_index (self, tu, request);
#ifdef IDE_ENABLE_TRACE
      ide_highlight_index_dump (index);
#endif
      break;

    case CXError_Failure:
      detail_error = _("Unknown failure");
      break;

    case CXError_Crashed:
      detail_error = _("Clang crashed");
      break;

    case CXError_InvalidArguments:
      detail_error = _("Invalid arguments");
      break;

    case CXError_ASTReadError:
      detail_error = _("AST read error");
      break;

    default:
      break;
    }

  if (!tu)
    {
      g_task_return_new_error (task,
                               G_IO_ERROR,
                               G_IO_ERROR_FAILED,
                               _("Failed to create translation unit: %s"),
                               detail_error ? detail_error : "");
      goto cleanup;
    }

  context = ide_object_get_context (source_object);
  gfile = ide_file_get_file (request->file);
  ret = _ide_clang_translation_unit_new (context, tu, gfile, index, request->sequence);

  g_task_return_pointer (task, g_object_ref (ret), g_object_unref);

cleanup:
  g_array_unref (ar);
}
static gpgme_key_t*
prompt_recipients (gpgme_key_t *signkey)
{
    gpgme_error_t gerr = 0;
    CryptUIKeyset *keyset;
    gpgme_ctx_t ctx;
    gpgme_key_t key;
    GArray *keys;
    gchar **recips;
    gchar *signer;

    *signkey = NULL;

    keyset = cryptui_keyset_new ("openpgp", TRUE);

    if (cryptui_keyset_get_count (keyset) == 0) {
        cryptui_need_to_get_keys ();
    } else {
        recips = cryptui_prompt_recipients (keyset, _("Choose Recipients"), &signer);

        if (recips) {
            gpgme_check_version (NULL);
            gerr = gpgme_engine_check_version (GPGME_PROTOCOL_OpenPGP);
            g_return_val_if_fail (gerr == 0, NULL);

            gerr = gpgme_new (&ctx);
            g_return_val_if_fail (gerr == 0, NULL);

            if (signer) {
                /* Load up the GPGME secret key */
                gchar *id = cryptui_keyset_key_raw_keyid (keyset, signer);
                gerr = gpgme_get_key (ctx, id, signkey, 1);
                g_free (id);

                /* A more descriptive error message */
                if (GPG_ERR_EOF == gpgme_err_code (gerr))
                    gerr = gpgme_error (GPG_ERR_NOT_FOUND);
            }

            if (gerr == 0) {
                gchar **ids;
                guint num;

                /* Load up the GPGME keys */
                ids = cryptui_keyset_keys_raw_keyids (keyset, (const gchar**)recips);
                num = g_strv_length (ids);
                keys = g_array_new (TRUE, TRUE, sizeof (gpgme_key_t));
                gerr = gpgme_op_keylist_ext_start (ctx, (const gchar**)ids, 0, 0);
                g_free (ids);

                if (gerr == 0) {
                    while ((gerr = gpgme_op_keylist_next (ctx, &key)) == 0)
                        g_array_append_val (keys, key);
                    gpgme_op_keylist_end (ctx);
                }

                /* Ignore EOF error */
                if (GPG_ERR_EOF == gpgme_err_code (gerr))
                    gerr = 0;

                if (gerr == 0 && num != keys->len)
                    g_warning ("couldn't load all the keys (%d/%d) from GPGME", keys->len, num);
            }

            gpgme_release (ctx);
        }

        g_object_unref (keyset);

        if (!recips)
            return NULL;

        g_strfreev (recips);
        g_free (signer);

        if (gerr == 0 && keys->len)
            return (gpgme_key_t*)g_array_free (keys, FALSE);

        /* When failure, free all our return values */
        seahorse_util_free_keys ((gpgme_key_t*)g_array_free (keys, FALSE));
        if (*signkey)
            gpgme_key_unref (*signkey);

        seahorse_util_handle_gpgme (gerr, _("Couldn't load keys"));
    }

    return NULL;
}
Esempio n. 5
0
static void
_gtk_css_image_linear_init (GtkCssImageLinear *linear)
{
  linear->stops = g_array_new (FALSE, FALSE, sizeof (GtkCssImageLinearColorStop));
  g_array_set_clear_func (linear->stops, gtk_css_image_clear_color_stop);
}
CK_RV
gkm_aes_mechanism_unwrap (GkmSession *session, CK_MECHANISM_PTR mech,
                          GkmObject *wrapper, CK_VOID_PTR input, CK_ULONG n_input,
                          CK_ATTRIBUTE_PTR attrs, CK_ULONG n_attrs,
                          GkmObject **unwrapped)
{
	gcry_cipher_hd_t cih;
	gcry_error_t gcry;
	CK_ATTRIBUTE attr;
	GArray *array;
	GkmAesKey *key;
	gpointer padded, value;
	gsize n_padded, n_value;
	GkmTransaction *transaction;
	gsize block, pos;
	gboolean ret;

	g_return_val_if_fail (GKM_IS_SESSION (session), CKR_GENERAL_ERROR);
	g_return_val_if_fail (mech, CKR_GENERAL_ERROR);
	g_return_val_if_fail (mech->mechanism == CKM_AES_CBC_PAD, CKR_GENERAL_ERROR);
	g_return_val_if_fail (GKM_IS_OBJECT (wrapper), CKR_GENERAL_ERROR);

	if (!GKM_IS_AES_KEY (wrapper))
		return CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
	key = GKM_AES_KEY (wrapper);

	block = gkm_aes_key_get_block_size (key);
	g_return_val_if_fail (block != 0, CKR_GENERAL_ERROR);

	if (n_input == 0 || n_input % block != 0)
		return CKR_WRAPPED_KEY_LEN_RANGE;

	cih = gkm_aes_key_get_cipher (key, GCRY_CIPHER_MODE_CBC);
	if (cih == NULL)
		return CKR_FUNCTION_FAILED;

	if (!mech->pParameter || gcry_cipher_setiv (cih, mech->pParameter, mech->ulParameterLen) != 0) {
		gcry_cipher_close (cih);
		return CKR_MECHANISM_PARAM_INVALID;
	}

	padded = egg_secure_alloc (n_input);
	memcpy (padded, input, n_input);
	n_padded = n_input;

	/* In place decryption */
	for (pos = 0; pos < n_padded; pos += block) {
		gcry = gcry_cipher_decrypt (cih, (guchar*)padded + pos, block, NULL, 0);
		g_return_val_if_fail (gcry == 0, CKR_GENERAL_ERROR);
	}

	gcry_cipher_close (cih);

	/* Unpad the resulting value */
	ret = egg_padding_pkcs7_unpad (egg_secure_realloc, block, padded, n_padded, &value, &n_value);
	egg_secure_free (padded);

	/* TODO: This is dubious, there doesn't seem to be an rv for 'bad decrypt' */
	if (ret == FALSE)
		return CKR_WRAPPED_KEY_INVALID;

	/* Now setup the attributes with our new value */
	array = g_array_new (FALSE, FALSE, sizeof (CK_ATTRIBUTE));

	/* Prepend the value */
	attr.type = CKA_VALUE;
	attr.pValue = value;
	attr.ulValueLen = n_value;
	g_array_append_val (array, attr);

	/* Add the remainder of the attributes */
	g_array_append_vals (array, attrs, n_attrs);

	transaction = gkm_transaction_new ();

	/* Now create an object with these attributes */
	*unwrapped = gkm_session_create_object_for_attributes (session, transaction,
	                                                       (CK_ATTRIBUTE_PTR)array->data, array->len);

	egg_secure_free (value);
	g_array_free (array, TRUE);

	return gkm_transaction_complete_and_unref (transaction);
}
Esempio n. 7
0
/*!
 \brief validate_and_load_tests() loads the list of tests from the system
 checks them for validity, and populates the passed array and hashtables
 with them
 \param tests is a pointer to a pointer of a GArray structure of the tests
 \param tests_hash is a pointer to a pointer of a hashtable of the Tests
 \returns TRUE on success, FALSE otherwise
 */
G_MODULE_EXPORT gboolean validate_and_load_tests(GArray **tests, GHashTable **tests_hash)
{
	ConfigFile *cfgfile;
	Detection_Test *test = NULL;
	gchar * filename = NULL;
	gchar *section = NULL;
	gchar * tmpbuf = NULL;
	gchar ** vector = NULL;
	gint total_tests = 0;
	gint result = 0;
	gint major = 0;
	gint minor = 0;
	gint i = 0;
	gint j = 0;

	filename = get_file(g_build_filename(INTERROGATOR_DATA_DIR,"Profiles",DATA_GET(global_data,"ecu_family"),"tests.cfg",NULL),NULL);
	if (!filename)
	{
		update_logbar_f("interr_view","warning",g_strdup_printf(_("Interrogation profile tests file %s not found!\n"),filename),FALSE,FALSE,TRUE);
		return FALSE;
	}

	cfgfile = cfg_open_file(filename);
	if (!cfgfile)
		return FALSE;
	get_file_api_f(cfgfile,&major,&minor);
	if ((major != INTERROGATE_MAJOR_API) || (minor != INTERROGATE_MINOR_API))
	{
		update_logbar_f("interr_view","warning",g_strdup_printf(_("Interrogation profile tests API mismatch (%i.%i != %i.%i):\n\tFile %s.\n"),major,minor,INTERROGATE_MAJOR_API,INTERROGATE_MINOR_API,filename),FALSE,FALSE,TRUE);
		g_free(filename);
		cfg_free(cfgfile);
		return FALSE;
	}

	*tests_hash = g_hash_table_new_full(g_str_hash,g_str_equal,NULL,test_cleanup);

	MTXDBG(INTERROGATOR,_("File %s, opened successfully\n"),filename);
	*tests = g_array_new(FALSE,TRUE,sizeof(Detection_Test *));
	cfg_read_int(cfgfile,"interrogation_tests","total_tests",&total_tests);
	for (i=0;i<total_tests;i++)
	{
		test = g_new0(Detection_Test, 1);
		section = g_strdup_printf("test_%.2i",i);
		if (!cfg_read_string(cfgfile,section,"test_name",&test->test_name))
		{
			MTXDBG(INTERROGATOR,_("test_name for %s is NULL\n"),section);
			g_free(section);
			break;
		}
		if (!cfg_read_string(cfgfile,section,"test_result_type",&tmpbuf))
		{
			MTXDBG(INTERROGATOR,_("test_result_type for %s is NULL\n"),section);
			g_free(section);
			break;
		}
		else
		{
			test->result_type = translate_string_f(tmpbuf);
			g_free(tmpbuf);
		}
		if (!cfg_read_string(cfgfile,section,"test_func",&test->test_func))
		{
			MTXDBG(INTERROGATOR,_("test_function for %s is NULL\n"),section);
			g_free(section);
			break;
		}
		get_symbol_f(test->test_func,(void *)&test->function);
		cfg_read_string(cfgfile,section,"test_desc",
				&test->test_desc);
		g_free(section);
		g_array_append_val(*tests,test);
		g_hash_table_insert(*tests_hash,test->test_name,test);
	}
	cfg_free(cfgfile);
	g_free(filename);
	return TRUE;
}
Esempio n. 8
0
void build_cpus_aml(Aml *table, MachineState *machine, CPUHotplugFeatures opts,
                    hwaddr io_base,
                    const char *res_root,
                    const char *event_handler_method)
{
    Aml *ifctx;
    Aml *field;
    Aml *method;
    Aml *cpu_ctrl_dev;
    Aml *cpus_dev;
    Aml *zero = aml_int(0);
    Aml *one = aml_int(1);
    Aml *sb_scope = aml_scope("_SB");
    MachineClass *mc = MACHINE_GET_CLASS(machine);
    CPUArchIdList *arch_ids = mc->possible_cpu_arch_ids(machine);
    char *cphp_res_path = g_strdup_printf("%s." CPUHP_RES_DEVICE, res_root);
    Object *obj = object_resolve_path_type("", TYPE_ACPI_DEVICE_IF, NULL);
    AcpiDeviceIfClass *adevc = ACPI_DEVICE_IF_GET_CLASS(obj);
    AcpiDeviceIf *adev = ACPI_DEVICE_IF(obj);

    cpu_ctrl_dev = aml_device("%s", cphp_res_path);
    {
        Aml *crs;

        aml_append(cpu_ctrl_dev,
            aml_name_decl("_HID", aml_eisaid("PNP0A06")));
        aml_append(cpu_ctrl_dev,
            aml_name_decl("_UID", aml_string("CPU Hotplug resources")));
        aml_append(cpu_ctrl_dev, aml_mutex(CPU_LOCK, 0));

        crs = aml_resource_template();
        aml_append(crs, aml_io(AML_DECODE16, io_base, io_base, 1,
                               ACPI_CPU_HOTPLUG_REG_LEN));
        aml_append(cpu_ctrl_dev, aml_name_decl("_CRS", crs));

        /* declare CPU hotplug MMIO region with related access fields */
        aml_append(cpu_ctrl_dev,
            aml_operation_region("PRST", AML_SYSTEM_IO, aml_int(io_base),
                                 ACPI_CPU_HOTPLUG_REG_LEN));

        field = aml_field("PRST", AML_BYTE_ACC, AML_NOLOCK,
                          AML_WRITE_AS_ZEROS);
        aml_append(field, aml_reserved_field(ACPI_CPU_FLAGS_OFFSET_RW * 8));
        /* 1 if enabled, read only */
        aml_append(field, aml_named_field(CPU_ENABLED, 1));
        /* (read) 1 if has a insert event. (write) 1 to clear event */
        aml_append(field, aml_named_field(CPU_INSERT_EVENT, 1));
        /* (read) 1 if has a remove event. (write) 1 to clear event */
        aml_append(field, aml_named_field(CPU_REMOVE_EVENT, 1));
        /* initiates device eject, write only */
        aml_append(field, aml_named_field(CPU_EJECT_EVENT, 1));
        aml_append(field, aml_reserved_field(4));
        aml_append(field, aml_named_field(CPU_COMMAND, 8));
        aml_append(cpu_ctrl_dev, field);

        field = aml_field("PRST", AML_DWORD_ACC, AML_NOLOCK, AML_PRESERVE);
        /* CPU selector, write only */
        aml_append(field, aml_named_field(CPU_SELECTOR, 32));
        /* flags + cmd + 2byte align */
        aml_append(field, aml_reserved_field(4 * 8));
        aml_append(field, aml_named_field(CPU_DATA, 32));
        aml_append(cpu_ctrl_dev, field);

        if (opts.has_legacy_cphp) {
            method = aml_method("_INI", 0, AML_SERIALIZED);
            /* switch off legacy CPU hotplug HW and use new one,
             * on reboot system is in new mode and writing 0
             * in CPU_SELECTOR selects BSP, which is NOP at
             * the time _INI is called */
            aml_append(method, aml_store(zero, aml_name(CPU_SELECTOR)));
            aml_append(cpu_ctrl_dev, method);
        }
    }
    aml_append(sb_scope, cpu_ctrl_dev);

    cpus_dev = aml_device("\\_SB.CPUS");
    {
        int i;
        Aml *ctrl_lock = aml_name("%s.%s", cphp_res_path, CPU_LOCK);
        Aml *cpu_selector = aml_name("%s.%s", cphp_res_path, CPU_SELECTOR);
        Aml *is_enabled = aml_name("%s.%s", cphp_res_path, CPU_ENABLED);
        Aml *cpu_cmd = aml_name("%s.%s", cphp_res_path, CPU_COMMAND);
        Aml *cpu_data = aml_name("%s.%s", cphp_res_path, CPU_DATA);
        Aml *ins_evt = aml_name("%s.%s", cphp_res_path, CPU_INSERT_EVENT);
        Aml *rm_evt = aml_name("%s.%s", cphp_res_path, CPU_REMOVE_EVENT);
        Aml *ej_evt = aml_name("%s.%s", cphp_res_path, CPU_EJECT_EVENT);

        aml_append(cpus_dev, aml_name_decl("_HID", aml_string("ACPI0010")));
        aml_append(cpus_dev, aml_name_decl("_CID", aml_eisaid("PNP0A05")));

        method = aml_method(CPU_NOTIFY_METHOD, 2, AML_NOTSERIALIZED);
        for (i = 0; i < arch_ids->len; i++) {
            Aml *cpu = aml_name(CPU_NAME_FMT, i);
            Aml *uid = aml_arg(0);
            Aml *event = aml_arg(1);

            ifctx = aml_if(aml_equal(uid, aml_int(i)));
            {
                aml_append(ifctx, aml_notify(cpu, event));
            }
            aml_append(method, ifctx);
        }
        aml_append(cpus_dev, method);

        method = aml_method(CPU_STS_METHOD, 1, AML_SERIALIZED);
        {
            Aml *idx = aml_arg(0);
            Aml *sta = aml_local(0);

            aml_append(method, aml_acquire(ctrl_lock, 0xFFFF));
            aml_append(method, aml_store(idx, cpu_selector));
            aml_append(method, aml_store(zero, sta));
            ifctx = aml_if(aml_equal(is_enabled, one));
            {
                aml_append(ifctx, aml_store(aml_int(0xF), sta));
            }
            aml_append(method, ifctx);
            aml_append(method, aml_release(ctrl_lock));
            aml_append(method, aml_return(sta));
        }
        aml_append(cpus_dev, method);

        method = aml_method(CPU_EJECT_METHOD, 1, AML_SERIALIZED);
        {
            Aml *idx = aml_arg(0);

            aml_append(method, aml_acquire(ctrl_lock, 0xFFFF));
            aml_append(method, aml_store(idx, cpu_selector));
            aml_append(method, aml_store(one, ej_evt));
            aml_append(method, aml_release(ctrl_lock));
        }
        aml_append(cpus_dev, method);

        method = aml_method(CPU_SCAN_METHOD, 0, AML_SERIALIZED);
        {
            Aml *else_ctx;
            Aml *while_ctx;
            Aml *has_event = aml_local(0);
            Aml *dev_chk = aml_int(1);
            Aml *eject_req = aml_int(3);
            Aml *next_cpu_cmd = aml_int(CPHP_GET_NEXT_CPU_WITH_EVENT_CMD);

            aml_append(method, aml_acquire(ctrl_lock, 0xFFFF));
            aml_append(method, aml_store(one, has_event));
            while_ctx = aml_while(aml_equal(has_event, one));
            {
                 /* clear loop exit condition, ins_evt/rm_evt checks
                  * will set it to 1 while next_cpu_cmd returns a CPU
                  * with events */
                 aml_append(while_ctx, aml_store(zero, has_event));
                 aml_append(while_ctx, aml_store(next_cpu_cmd, cpu_cmd));
                 ifctx = aml_if(aml_equal(ins_evt, one));
                 {
                     aml_append(ifctx,
                         aml_call2(CPU_NOTIFY_METHOD, cpu_data, dev_chk));
                     aml_append(ifctx, aml_store(one, ins_evt));
                     aml_append(ifctx, aml_store(one, has_event));
                 }
                 aml_append(while_ctx, ifctx);
                 else_ctx = aml_else();
                 ifctx = aml_if(aml_equal(rm_evt, one));
                 {
                     aml_append(ifctx,
                         aml_call2(CPU_NOTIFY_METHOD, cpu_data, eject_req));
                     aml_append(ifctx, aml_store(one, rm_evt));
                     aml_append(ifctx, aml_store(one, has_event));
                 }
                 aml_append(else_ctx, ifctx);
                 aml_append(while_ctx, else_ctx);
            }
            aml_append(method, while_ctx);
            aml_append(method, aml_release(ctrl_lock));
        }
        aml_append(cpus_dev, method);

        method = aml_method(CPU_OST_METHOD, 4, AML_SERIALIZED);
        {
            Aml *uid = aml_arg(0);
            Aml *ev_cmd = aml_int(CPHP_OST_EVENT_CMD);
            Aml *st_cmd = aml_int(CPHP_OST_STATUS_CMD);

            aml_append(method, aml_acquire(ctrl_lock, 0xFFFF));
            aml_append(method, aml_store(uid, cpu_selector));
            aml_append(method, aml_store(ev_cmd, cpu_cmd));
            aml_append(method, aml_store(aml_arg(1), cpu_data));
            aml_append(method, aml_store(st_cmd, cpu_cmd));
            aml_append(method, aml_store(aml_arg(2), cpu_data));
            aml_append(method, aml_release(ctrl_lock));
        }
        aml_append(cpus_dev, method);

        /* build Processor object for each processor */
        for (i = 0; i < arch_ids->len; i++) {
            int j;
            Aml *dev;
            Aml *uid = aml_int(i);
            GArray *madt_buf = g_array_new(0, 1, 1);
            int arch_id = arch_ids->cpus[i].arch_id;

            if (opts.apci_1_compatible && arch_id < 255) {
                dev = aml_processor(i, 0, 0, CPU_NAME_FMT, i);
            } else {
                dev = aml_device(CPU_NAME_FMT, i);
                aml_append(dev, aml_name_decl("_HID", aml_string("ACPI0007")));
                aml_append(dev, aml_name_decl("_UID", uid));
            }

            method = aml_method("_STA", 0, AML_SERIALIZED);
            aml_append(method, aml_return(aml_call1(CPU_STS_METHOD, uid)));
            aml_append(dev, method);

            /* build _MAT object */
            assert(adevc && adevc->madt_cpu);
            adevc->madt_cpu(adev, i, arch_ids, madt_buf);
            switch (madt_buf->data[0]) {
            case ACPI_APIC_PROCESSOR: {
                AcpiMadtProcessorApic *apic = (void *)madt_buf->data;
                apic->flags = cpu_to_le32(1);
                break;
            }
            default:
                assert(0);
            }
            aml_append(dev, aml_name_decl("_MAT",
                aml_buffer(madt_buf->len, (uint8_t *)madt_buf->data)));
            g_array_free(madt_buf, true);

            method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);
            aml_append(method, aml_call1(CPU_EJECT_METHOD, uid));
            aml_append(dev, method);

            method = aml_method("_OST", 3, AML_SERIALIZED);
            aml_append(method,
                aml_call4(CPU_OST_METHOD, uid, aml_arg(0),
                          aml_arg(1), aml_arg(2))
            );
            aml_append(dev, method);

            /* Linux guests discard SRAT info for non-present CPUs
             * as a result _PXM is required for all CPUs which might
             * be hot-plugged. For simplicity, add it for all CPUs.
             */
            j = numa_get_node_for_cpu(i);
            if (j < nb_numa_nodes) {
                aml_append(dev, aml_name_decl("_PXM", aml_int(j)));
            }

            aml_append(cpus_dev, dev);
        }
    }
    aml_append(sb_scope, cpus_dev);
    aml_append(table, sb_scope);

    method = aml_method(event_handler_method, 0, AML_NOTSERIALIZED);
    aml_append(method, aml_call0("\\_SB.CPUS." CPU_SCAN_METHOD));
    aml_append(table, method);

    g_free(cphp_res_path);
    g_free(arch_ids);
}
Esempio n. 9
0
/* Punycode decoder, RFC 3492 section 6.2. As with punycode_encode(),
 * read the RFC if you want to understand what this is actually doing.
 */
static gboolean
punycode_decode (const gchar *input,
                 gsize        input_length,
                 GString     *output)
{
  GArray *output_chars;
  gunichar n;
  guint i, bias;
  guint oldi, w, k, digit, t;
  const gchar *split;

  n = PUNYCODE_INITIAL_N;
  i = 0;
  bias = PUNYCODE_INITIAL_BIAS;

  split = input + input_length - 1;
  while (split > input && *split != '-')
    split--;
  if (split > input)
    {
      output_chars = g_array_sized_new (FALSE, FALSE, sizeof (gunichar),
					split - input);
      input_length -= (split - input) + 1;
      while (input < split)
	{
	  gunichar ch = (gunichar)*input++;
	  if (!PUNYCODE_IS_BASIC (ch))
	    goto fail;
	  g_array_append_val (output_chars, ch);
	}
      input++;
    }
  else
    output_chars = g_array_new (FALSE, FALSE, sizeof (gunichar));

  while (input_length)
    {
      oldi = i;
      w = 1;
      for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE)
	{
	  if (!input_length--)
	    goto fail;
	  digit = decode_digit (*input++);
	  if (digit >= PUNYCODE_BASE)
	    goto fail;
	  if (digit > (G_MAXUINT - i) / w)
	    goto fail;
	  i += digit * w;
	  if (k <= bias)
	    t = PUNYCODE_TMIN;
	  else if (k >= bias + PUNYCODE_TMAX)
	    t = PUNYCODE_TMAX;
	  else
	    t = k - bias;
	  if (digit < t)
	    break;
	  if (w > G_MAXUINT / (PUNYCODE_BASE - t))
	    goto fail;
	  w *= (PUNYCODE_BASE - t);
	}

      bias = adapt (i - oldi, output_chars->len + 1, oldi == 0);

      if (i / (output_chars->len + 1) > G_MAXUINT - n)
	goto fail;
      n += i / (output_chars->len + 1);
      i %= (output_chars->len + 1);

      g_array_insert_val (output_chars, i++, n);
    }

  for (i = 0; i < output_chars->len; i++)
    g_string_append_unichar (output, g_array_index (output_chars, gunichar, i));
  g_array_free (output_chars, TRUE);
  return TRUE;

 fail:
  g_array_free (output_chars, TRUE);
  return FALSE;
}
Esempio n. 10
0
GumHeapApiList *
gum_heap_api_list_new (void)
{
  return g_array_new (FALSE, FALSE, sizeof (GumHeapApi));
}
Esempio n. 11
0
int main(int argc, char * argv[]){
    int i = 1;
    bool gen_extra_enter = false;

    setlocale(LC_ALL, "");
    //deal with options.
    while ( i < argc ){
        if ( strcmp ("--help", argv[i]) == 0) {
            print_help();
            exit(0);
        } else if (strcmp("--generate-extra-enter", argv[i]) == 0) {
            gen_extra_enter = true;
        } else {
            print_help();
            exit(EINVAL);
        }
        ++i;
    }

    //init phrase table
    PhraseLargeTable phrase_table;
    MemoryChunk * chunk = new MemoryChunk;
    chunk->load("phrase_index.bin");
    phrase_table.load(chunk);

    char * linebuf = NULL;
    size_t size = 0;
    ssize_t read;
    while( (read = getline(&linebuf, &size, stdin)) != -1 ){
        if ( '\n' ==  linebuf[strlen(linebuf) - 1] ) {
            linebuf[strlen(linebuf) - 1] = '\0';
        }

        //check non-ucs2 characters
        const glong num_of_chars = g_utf8_strlen(linebuf, -1);
        glong len = 0;
        utf16_t * sentence = g_utf8_to_utf16(linebuf, -1, NULL, &len, NULL);
        if ( len != num_of_chars ) {
            fprintf(stderr, "non-ucs2 characters encountered:%s.\n", linebuf);
            printf("\n");
            continue;
        }

        //do segment stuff
        GArray * strings = g_array_new(TRUE, TRUE, sizeof(SegmentStep));
        segment(&phrase_table, sentence, len, strings);

        //print out the split phrase
        for ( glong i = 0; i < strings->len; ++i ) {
            SegmentStep * step = &g_array_index(strings, SegmentStep, i);
            char * string = g_utf16_to_utf8( step->m_phrase, step->m_phrase_len, NULL, NULL, NULL);
            printf("%s\n", string);
            g_free(string);
        }

        /* print extra enter */
        if ( gen_extra_enter )
            printf("\n");

        g_array_free(strings, TRUE);
        g_free(sentence);
    }

    /* print enter at file tail */
    printf("\n");
    return 0;
}
			fec_info_column(f->fec, pinfo);
	}
	return offset;
}

static guint dissect_norm_hdrext(struct _norm *norm, struct _fec_ptr *f, proto_tree *tree,
							 tvbuff_t *tvb, guint offset, packet_info *pinfo _U_)
{
	guint i;
	proto_item *ti;
	/* Allocate an array of _ext elements */
	GArray *ext;
	guint offset_old = offset;
	proto_tree *ext_tree;

	ext = g_array_new(FALSE, TRUE, sizeof(struct _ext));

	rmt_ext_parse(ext, tvb, &offset, hdrlen2bytes(norm->hlen));

	if (ext->len > 0)
	{
		struct _lct_prefs lctp;
		memset(&lctp, 0, sizeof(lctp));
		if (tree)
		{
			/* Add the extensions subtree */
			ti = proto_tree_add_uint(tree, hf.extension,
				tvb, offset_old,
				offset - offset_old, ext->len);
			ext_tree = proto_item_add_subtree(ti, ett.hdrext);
		} else
Esempio n. 13
0
static void
collect_sessions (void)
{
        g_autoptr(GHashTable) names_seen_before = NULL;
        GArray     *xorg_search_array = NULL;
        GArray     *wayland_search_array = NULL;
        gchar      *session_dir = NULL;
        int         i;
        const char *xorg_search_dirs[] = {
                "/etc/X11/sessions/",
                DMCONFDIR "/Sessions/",
                DATADIR "/gdm/BuiltInSessions/",
                DATADIR "/xsessions/",
        };

        names_seen_before = g_hash_table_new (g_str_hash, g_str_equal);

        xorg_search_array = g_array_new (TRUE, TRUE, sizeof (char *));

        const gchar * const *system_data_dirs = g_get_system_data_dirs ();

        for (i = 0; system_data_dirs[i]; i++) {
                session_dir = g_build_filename (system_data_dirs[i], "xsessions", NULL);
                g_array_append_val (xorg_search_array, session_dir);
        }

        g_array_append_vals (xorg_search_array, xorg_search_dirs, G_N_ELEMENTS (xorg_search_dirs));

#ifdef ENABLE_WAYLAND_SUPPORT
        const char *wayland_search_dirs[] = {
                DATADIR "/wayland-sessions/",
        };

        wayland_search_array = g_array_new (TRUE, TRUE, sizeof (char *));

        for (i = 0; system_data_dirs[i]; i++) {
                session_dir = g_build_filename (system_data_dirs[i], "wayland-sessions", NULL);
                g_array_append_val (wayland_search_array, session_dir);
        }

        g_array_append_vals (wayland_search_array, wayland_search_dirs, G_N_ELEMENTS (wayland_search_dirs));
#endif

        if (gdm_available_sessions_map == NULL) {
                gdm_available_sessions_map = g_hash_table_new_full (g_str_hash, g_str_equal,
                                                                    g_free, (GDestroyNotify)gdm_session_file_free);
        }

        for (i = 0; i < xorg_search_array->len; i++) {
                collect_sessions_from_directory (g_array_index (xorg_search_array, gchar*, i));
        }

        g_array_free (xorg_search_array, TRUE);

#ifdef ENABLE_WAYLAND_SUPPORT
#ifdef ENABLE_USER_DISPLAY_SERVER
        if (g_getenv ("WAYLAND_DISPLAY") == NULL && g_getenv ("RUNNING_UNDER_GDM") != NULL) {
                g_array_free (wayland_search_array, TRUE);
                return;
        }
#endif

        for (i = 0; i < wayland_search_array->len; i++) {
                collect_sessions_from_directory (g_array_index (wayland_search_array, gchar*, i));
        }

        g_array_free (wayland_search_array, TRUE);
#endif

        g_hash_table_foreach_remove (gdm_available_sessions_map,
                                     remove_duplicate_sessions,
                                     names_seen_before);
}
Esempio n. 14
0
/*
 * Create clone IDBs for the merge file, based on the input files and mode.
 */
static wtapng_iface_descriptions_t *
generate_merged_idb(merge_in_file_t *in_files, const guint in_file_count, const idb_merge_mode mode)
{
    wtapng_iface_descriptions_t *merged_idb_list = NULL;
    wtapng_iface_descriptions_t *input_file_idb_list = NULL;
    const wtapng_if_descr_t     *input_file_idb = NULL;
    guint                        itf_count, merged_index;
    guint                        i;

    /* create new IDB info */
    merged_idb_list = g_new(wtapng_iface_descriptions_t,1);
    merged_idb_list->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));

    if (mode == IDB_MERGE_MODE_ALL_SAME && all_idbs_are_duplicates(in_files, in_file_count)) {
        guint num_idbs;

        merge_debug("merge::generate_merged_idb: mode ALL set and all IDBs are duplicates");

        /* they're all the same, so just get the first file's IDBs */
        input_file_idb_list = wtap_file_get_idb_info(in_files[0].wth);
        /* this is really one more than number of IDBs, but that's good for the for-loops */
        num_idbs = input_file_idb_list->interface_data->len;

        /* put them in the merged file */
        for (itf_count = 0; itf_count < num_idbs; itf_count++) {
            input_file_idb = &g_array_index(input_file_idb_list->interface_data,
                                            wtapng_if_descr_t, itf_count);
            merged_index = add_idb_to_merged_file(merged_idb_list, input_file_idb);
            add_idb_index_map(&in_files[0], itf_count, merged_index);
        }

        /* and set all the other file index maps the same way */
        for (i = 1; i < in_file_count; i++) {
            for (itf_count = 0; itf_count < num_idbs; itf_count++) {
                add_idb_index_map(&in_files[i], itf_count, itf_count);
            }
        }

        g_free(input_file_idb_list);
    }
    else {
        for (i = 0; i < in_file_count; i++) {
            input_file_idb_list = wtap_file_get_idb_info(in_files[i].wth);

            for (itf_count = 0; itf_count < input_file_idb_list->interface_data->len; itf_count++) {
                input_file_idb = &g_array_index(input_file_idb_list->interface_data,
                                                wtapng_if_descr_t, itf_count);

                if (mode == IDB_MERGE_MODE_ANY_SAME &&
                    find_duplicate_idb(input_file_idb, merged_idb_list, &merged_index))
                {
                    merge_debug("merge::generate_merged_idb: mode ANY set and found a duplicate");
                    /*
                     * It's the same as a previous IDB, so we're going to "merge"
                     * them into one by adding a map from its old IDB index to the new
                     * one. This will be used later to change the phdr interface_id.
                     */
                    add_idb_index_map(&in_files[i], itf_count, merged_index);
                }
                else {
                    merge_debug("merge::generate_merged_idb: mode NONE set or did not find a duplicate");
                    /*
                     * This IDB does not match a previous (or we want to save all IDBs),
                     * so add the IDB to the merge file, and add a map of the indeces.
                     */
                    merged_index = add_idb_to_merged_file(merged_idb_list, input_file_idb);
                    add_idb_index_map(&in_files[i], itf_count, merged_index);
                }
            }

            g_free(input_file_idb_list);
        }
    }

    return merged_idb_list;
}
Esempio n. 15
0
static void
gbl_symbols_new(void)
{
  DISSECTOR_ASSERT(gbl_symbols_array == NULL);
  gbl_symbols_array = g_array_new(TRUE, TRUE, sizeof(value_string));
}
Esempio n. 16
0
/*
 * recurse == 1: don't expand '@(command)@'
 * recurse == 2: don't expand '@<java script>@'
*/
gchar*
expand(const char* s, guint recurse) {
    enum exp_type etype;
    char*         end_simple_var = "\t^°!\"§$%&/()=?'`'+~*'#-:,;@<>| \\{}[]¹²³¼½";
    char*         ret = NULL;
    char*         vend = NULL;
    GError*       err = NULL;
    gchar*        cmd_stdout = NULL;
    gchar*        mycmd = NULL;
    GString*      buf = g_string_new("");
    GString*      js_ret = g_string_new("");

    while (s && *s) {
        switch(*s) {
            case '\\':
                g_string_append_c(buf, *++s);
                s++;
                break;

            case '@':
                etype = get_exp_type(s);
                s++;

                switch(etype) {
                    case EXP_SIMPLE_VAR:
                        vend = strpbrk(s, end_simple_var);
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_BRACED_VAR:
                        s++;
                        vend = strchr(s, '}');
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_EXPR:
                        s++;
                        vend = strstr(s, ")@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_JS:
                        s++;
                        vend = strstr(s, ">@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    case EXP_ESCAPE:
                        s++;
                        vend = strstr(s, "]@");
                        if(!vend) vend = strchr(s, '\0');
                        break;
                    /*@notreached@*/
                    case EXP_ERR:
                        break;
                }
                assert(vend);

                ret = g_strndup(s, vend-s);

                if(etype == EXP_SIMPLE_VAR ||
                   etype == EXP_BRACED_VAR) {

                    expand_variable(buf, ret);

                    if(etype == EXP_SIMPLE_VAR)
                        s = vend;
                    else
                        s = vend+1;
                }
                else if(recurse != 1 &&
                        etype == EXP_EXPR) {

                    /* execute program directly */
                    if(ret[0] == '+') {
                        mycmd = expand(ret+1, 1);
                        g_spawn_command_line_sync(mycmd, &cmd_stdout, NULL, NULL, &err);
                        g_free(mycmd);
                    }
                    /* execute program through shell, quote it first */
                    else {
                        mycmd = expand(ret, 1);
                        gchar *quoted = g_shell_quote(mycmd);
                        gchar *tmp = g_strdup_printf("%s %s",
                                uzbl.behave.shell_cmd?uzbl.behave.shell_cmd:"/bin/sh -c",
                                quoted);
                        g_spawn_command_line_sync(tmp, &cmd_stdout, NULL, NULL, &err);
                        g_free(mycmd);
                        g_free(quoted);
                        g_free(tmp);
                    }

                    if (err) {
                        g_printerr("error on running command: %s\n", err->message);
                        g_error_free (err);
                    }
                    else if (*cmd_stdout) {
                        size_t len = strlen(cmd_stdout);

                        if(len > 0 && cmd_stdout[len-1] == '\n')
                            cmd_stdout[--len] = '\0'; /* strip trailing newline */

                        g_string_append(buf, cmd_stdout);
                        g_free(cmd_stdout);
                    }
                    s = vend+2;
                }
                else if(recurse != 2 &&
                        etype == EXP_JS) {

                    /* read JS from file */
                    if(ret[0] == '+') {
                        GArray *tmp = g_array_new(TRUE, FALSE, sizeof(gchar *));
                        mycmd = expand(ret+1, 2);
                        g_array_append_val(tmp, mycmd);

                        run_external_js(uzbl.gui.web_view, tmp, js_ret);
                        g_array_free(tmp, TRUE);
                    }
                    /* JS from string */
                    else {
                        mycmd = expand(ret, 2);
                        eval_js(uzbl.gui.web_view, mycmd, js_ret, "(command)");
                        g_free(mycmd);
                    }

                    if(js_ret->str) {
                        g_string_append(buf, js_ret->str);
                        g_string_free(js_ret, TRUE);
                        js_ret = g_string_new("");
                    }
                    s = vend+2;
                }
                else if(etype == EXP_ESCAPE) {
                    mycmd = expand(ret, 0);
                    char *escaped = g_markup_escape_text(mycmd, strlen(mycmd));

                    g_string_append(buf, escaped);

                    g_free(escaped);
                    g_free(mycmd);
                    s = vend+2;
                }

                g_free(ret);
                ret = NULL;
                break;

            default:
                g_string_append_c(buf, *s);
                s++;
                break;
        }
    }
    g_string_free(js_ret, TRUE);
    return g_string_free(buf, FALSE);
}
Esempio n. 17
0
UString*
ustring_new()
{
    return g_array_new(TRUE, TRUE, sizeof(ucschar));
}