static void
test_mapping (void)
{
  GMappedFile *map;

  write_or_die (filename, "ABC", -1);

  map = map_or_die (filename, FALSE);
  g_assert (g_mapped_file_get_length (map) == 3);
  g_mapped_file_free (map);

  map = map_or_die (filename, TRUE);
  g_assert (g_mapped_file_get_length (map) == 3);
  g_mapped_file_free (map);
}
Example #2
0
File: vtetc.c Project: Cordia/vte
static void
_vte_termcap_destroy (VteTermcap *termcap)
{
  g_tree_destroy (termcap->tree);
  g_mapped_file_free (termcap->file);
  g_slice_free (VteTermcap, termcap);
}
Example #3
0
static void 
test_private (void)
{
  GError *error = NULL;
  GMappedFile *map;
  gchar *buffer;
  gsize len;

  write_or_die (filename, "ABC", -1);
  map = map_or_die (filename, TRUE);

  buffer = (gchar *)g_mapped_file_get_contents (map);
  buffer[0] = '1';
  buffer[1] = '2';
  buffer[2] = '3';
  g_mapped_file_free (map);

  if (!g_file_get_contents (filename, &buffer, &len, &error))
    {
      g_print ("failed to read '%s': %s\n", 
	       displayname, error->message);
      exit (1);
      
    }
  g_assert (len == 3);
  g_assert (strcmp (buffer, "ABC") == 0);
  g_free (buffer);

  g_message ("test_private: ok");
}
Example #4
0
static gboolean
zone_info_read(const gchar *zonename, ZoneInfo **zone, ZoneInfo **zone64)
{
  unsigned char *buff = NULL;
  gchar *filename = NULL; 
  int byte_read = 0;
  int version;
  GError *error = NULL;
  GMappedFile *file_map = NULL;

  *zone = NULL;
  *zone64 = NULL;

  filename = g_build_path(G_DIR_SEPARATOR_S, get_time_zone_basedir(), zonename, NULL);

  file_map = g_mapped_file_new(filename, FALSE, &error);
  if (!file_map)
    {
      msg_error("Failed to open the time zone file", evt_tag_str("filename", filename), evt_tag_str("message", error->message), NULL);
      g_error_free(error);
      g_free(filename);
      return FALSE;
    }

  byte_read = g_mapped_file_get_length(file_map);
  buff = (unsigned char*)g_mapped_file_get_contents(file_map);

  if (byte_read == -1)
    {
      msg_error("Failed to read the time zone file", evt_tag_str("filename", filename), NULL);
      g_mapped_file_free(file_map);
      g_free(filename);
      return FALSE;
    }

  msg_debug("Processing the time zone file (32bit part)", evt_tag_str("filename", filename), NULL);
  *zone = zone_info_parser(&buff, FALSE, &version);
  if (version == 2)
    {
      msg_debug("Processing the time zone file (64bit part)", evt_tag_str("filename", filename), NULL);
      *zone64 = zone_info_parser(&buff, TRUE, &version);
    }

  g_mapped_file_free(file_map);
    g_free(filename);
  return TRUE;
}
static void
test_child_private (gchar *argv0)
{
  GError *error = NULL;
  GMappedFile *map;
  gchar *buffer;
  gsize len;
  gchar *child_argv[3];
  GPid  child_pid;
  
#ifdef G_OS_WIN32
  g_remove ("STOP");
  g_assert (!g_file_test ("STOP", G_FILE_TEST_EXISTS));
#endif

  write_or_die (filename, "ABC", -1);
  map = map_or_die (filename, TRUE);

  child_argv[0] = argv0;
  child_argv[1] = "mapchild";
  child_argv[2] = NULL;
  if (!g_spawn_async (dir, child_argv, NULL,
		      0, NULL, NULL, &child_pid, &error))
    {
      g_print ("failed to spawn child: %s\n", 
	       error->message);
      exit (1);            
    }

  /* give the child some time to set up its mapping */
  g_usleep (2000000);

  buffer = (gchar *)g_mapped_file_get_contents (map);
  buffer[0] = '1';
  buffer[1] = '2';
  buffer[2] = '3';
  g_mapped_file_free (map);

#ifndef G_OS_WIN32
  kill (child_pid, SIGUSR1);
#else
  g_file_set_contents ("STOP", "Hey there\n", -1, NULL);
#endif

  /* give the child some time to write the file */
  g_usleep (2000000);

  if (!g_file_get_contents (childname, &buffer, &len, &error))
    {
      gchar *name;

      name = g_filename_display_name (childname);
      g_print ("failed to read '%s': %s\n", name, error->message);
      exit (1);      
    }
  g_assert (len == 3);
  g_assert (strcmp (buffer, "ABC") == 0);
  g_free (buffer);
}
Example #6
0
GList *
empathy_log_manager_search_new (EmpathyLogManager *manager,
				const gchar       *text)
{
	GList *files, *l;
	GList *hits = NULL;
	gchar *text_casefold;

	g_return_val_if_fail (EMPATHY_IS_LOG_MANAGER (manager), NULL);
	g_return_val_if_fail (!EMP_STR_EMPTY (text), NULL);

	text_casefold = g_utf8_casefold (text, -1);

	files = log_manager_get_all_files (manager, NULL);
	DEBUG ("Found %d log files in total", g_list_length (files));

	for (l = files; l; l = l->next) {
		gchar       *filename;
		GMappedFile *file;
		gsize        length;
		gchar       *contents;
		gchar       *contents_casefold;

		filename = l->data;

		file = g_mapped_file_new (filename, FALSE, NULL);
		if (!file) {
			continue;
		}

		length = g_mapped_file_get_length (file);
		contents = g_mapped_file_get_contents (file);
		contents_casefold = g_utf8_casefold (contents, length);

		g_mapped_file_free (file);

		if (strstr (contents_casefold, text_casefold)) {
			EmpathyLogSearchHit *hit;

			hit = log_manager_search_hit_new (manager, filename);

			if (hit) {
				hits = g_list_prepend (hits, hit);
				DEBUG ("Found text:'%s' in file:'%s' on date:'%s'",
					text, hit->filename, hit->date);
			}
		}

		g_free (contents_casefold);
		g_free (filename);
	}
	g_list_free (files);

	g_free (text_casefold);

	return hits;
}
Example #7
0
static int
compare_files(const gchar *f1, const gchar *f2) {
  GError *error = NULL;
  GMappedFile *file1 = NULL, *file2 = NULL;
  int err;

  file1 = g_mapped_file_new (f1, FALSE, &error);
  if (error != NULL) {
    file1 = NULL;
    err = -1;
    goto out_err;
  }

  file2 = g_mapped_file_new (f2, FALSE, &error);
  if (error != NULL) {
    file2 = NULL;
    err = -1;
    goto out_err;
  }

  /* Then update */
  err = compare_data(g_mapped_file_get_contents (file1),
		     g_mapped_file_get_length (file1),
		     g_mapped_file_get_contents (file2),
		     g_mapped_file_get_length (file2));

  goto out;

  out_err:
    g_warning ("error opening file: %s",error->message);
    g_error_free (error);
  out:
    if (file1)
      g_mapped_file_free (file1);
    if (file2)
      g_mapped_file_free (file2);
    return err;
}
Example #8
0
xmlDocPtr
e_xml_parse_file (const char *filename)
{
	xmlDocPtr result = NULL;

	GMappedFile *mapped_file;

	mapped_file = g_mapped_file_new (filename, FALSE, NULL);
	if (mapped_file) {
		result = xmlParseMemory (g_mapped_file_get_contents (mapped_file),
					 g_mapped_file_get_length (mapped_file));
		g_mapped_file_free (mapped_file);
	}
	return result;
}
Example #9
0
void
_gtk_icon_cache_unref (GtkIconCache *cache)
{
  cache->ref_count --;

  if (cache->ref_count == 0)
    {
      GTK_NOTE (ICONTHEME, 
		g_print ("unmapping icon cache\n"));

      if (cache->map)
	g_mapped_file_free (cache->map);
      g_free (cache);
    }
}
Example #10
0
/** Destructor for GncCsvParseData.
 * @param parse_data Parse data whose memory will be freed
 */
void gnc_csv_parse_data_free(GncCsvParseData* parse_data)
{
    /* All non-NULL pointers have been initialized and must be freed. */

    if (parse_data->raw_mapping != NULL)
        g_mapped_file_free(parse_data->raw_mapping);

    if (parse_data->file_str.begin != NULL)
        g_free(parse_data->file_str.begin);

    if (parse_data->orig_lines != NULL)
        stf_parse_general_free(parse_data->orig_lines);

    if (parse_data->orig_row_lengths != NULL)
        g_array_free(parse_data->orig_row_lengths, FALSE);

    if (parse_data->options != NULL)
        stf_parse_options_free(parse_data->options);

    if (parse_data->column_types != NULL)
        g_array_free(parse_data->column_types, TRUE);

    if (parse_data->error_lines != NULL)
        g_list_free(parse_data->error_lines);

    if (parse_data->transactions != NULL)
    {
        GList* transactions = parse_data->transactions;
        /* We have to free the GncCsvTransLine's that are at each node in
         * the list before freeing the entire list. */
        do
        {
            g_free(transactions->data);
            transactions = g_list_next(transactions);
        }
        while (transactions != NULL);
        g_list_free(parse_data->transactions);
    }

    g_free(parse_data->chunk);
    g_free(parse_data);
}
Example #11
0
/*  Replacement for exif_data_new_from_file() to work around
 *  filename encoding problems (see bug #335391).
 */
ExifData *
jpeg_exif_data_new_from_file (const gchar  *filename,
                              GError      **error)
{
  ExifData    *data;
  GMappedFile *file;

  g_return_val_if_fail (filename != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  file = g_mapped_file_new (filename, FALSE, error);
  if (! file)
    return NULL;

  data = exif_data_new_from_data ((guchar *) g_mapped_file_get_contents (file),
                                  g_mapped_file_get_length (file));

  g_mapped_file_free (file);

  return data;
}
Example #12
0
int main(int argc, char *argv[])
{
  int size;
  int nErr=0;
  char buf[1024];
  char *phont_path = NULL;
  
  if (argc == 2) {
    GRand *g_rnd = g_rand_new();
    int nphont = g_rand_int_range(g_rnd, 0, 10);
    g_print("%d\n", nphont);
    phont_path = phont_files[nphont];
  } else if (argc == 3){
    phont_path = argv[2];
  }else {
    printf ("HelloTalk [talk string] [phont file path]");
    return 0;
  }

  void* p=AqKanji2Koe_Create("./aq_dic", &nErr);
  if (p==NULL){
    printf("error\n");
  }
  AqKanji2Koe_Convert(p, argv[1], buf, 1024);
  printf("%s\n", buf);

  
  GError *perr = NULL;
  GMappedFile *gmap=NULL;
  g_print("%s\n", phont_path);
  gmap = g_mapped_file_new(phont_path, FALSE, &perr);
  if (gmap!=NULL){
    gchar *pc = g_mapped_file_get_contents(gmap);
    AquesTalk2Da_PlaySync(buf, 100, pc);
    g_mapped_file_free(gmap);
  }

  AqKanji2Koe_Release(p);
  return 0;
}
Example #13
0
static gboolean
to64 (const gchar  *filename,
      FILE         *outfile,
      GError      **error)
{
  GMappedFile  *infile;
  const guchar *in;
  gchar         out[2048];
  gint          state = 0;
  gint          save  = 0;
  gsize         len;
  gsize         bytes;
  gsize         c;

  infile = g_mapped_file_new (filename, FALSE, error);
  if (! infile)
    return FALSE;

  in = (const guchar *) g_mapped_file_get_contents (infile);
  len = g_mapped_file_get_length (infile);

  for (c = 0; c < len;)
    {
      gsize step = MIN (1024, len - c);

      bytes = g_base64_encode_step (in + c, step, TRUE, out, &state, &save);
      fwrite (out, 1, bytes, outfile);

      c += step;
    }

  bytes = g_base64_encode_close (TRUE, out, &state, &save);
  fwrite (out, 1, bytes, outfile);

  g_mapped_file_free (infile);

  return TRUE;
}
Example #14
0
static GSList* parse(const gchar* fn)
{
    GMappedFile* f = g_mapped_file_new(fn, FALSE, NULL);
    GSList*      atoms = NULL;

    if ( f ) {
        gchar** lns = g_strsplit(g_mapped_file_get_contents(f), "\n", -1);
        guint   i = 0;
        
        for ( ; NULL != lns[i]; i++ ) {
            const gchar* ln = g_strstrip(lns[i]);
            Atom*        a = parse_line(ln);

            if ( a ) {
                atoms = g_slist_append(atoms, a);
            }
        }

        g_strfreev(lns);
        g_mapped_file_free(f);
    }
    
    return atoms;
}
Example #15
0
static gboolean google_goto_tool_parse_file_for_latlon(VikGotoTool *self, gchar *file_name, struct LatLon *ll)
{
    gchar *text, *pat;
    GMappedFile *mf;
    gsize len;
    gboolean found = TRUE;
    gchar lat_buf[32], lon_buf[32];
    gchar *s;

    lat_buf[0] = lon_buf[0] = '\0';

    if ((mf = g_mapped_file_new(file_name, FALSE, NULL)) == NULL) {
        g_critical(_("couldn't map temp file"));
        exit(1);
    }
    len = g_mapped_file_get_length(mf);
    text = g_mapped_file_get_contents(mf);

    if (g_strstr_len(text, len, GOOGLE_GOTO_NOT_FOUND) != NULL) {
        found = FALSE;
        goto done;
    }

    if ((pat = g_strstr_len(text, len, GOOGLE_GOTO_PATTERN_1)) == NULL) {
        found = FALSE;
        goto done;
    }
    pat += strlen(GOOGLE_GOTO_PATTERN_1);
    s = lat_buf;
    if (*pat == '-')
        *s++ = *pat++;
    while ((s < (lat_buf + sizeof(lat_buf))) && (pat < (text + len)) &&
            (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
    *s = '\0';
    if ((pat >= (text + len)) || (lat_buf[0] == '\0')) {
        found = FALSE;
        goto done;
    }

    if (strncmp(pat, GOOGLE_GOTO_PATTERN_2, strlen(GOOGLE_GOTO_PATTERN_2))) {
        found = FALSE;
        goto done;
    }

    pat += strlen(GOOGLE_GOTO_PATTERN_2);
    s = lon_buf;

    if (*pat == '-')
        *s++ = *pat++;
    while ((s < (lon_buf + sizeof(lon_buf))) && (pat < (text + len)) &&
            (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
    *s = '\0';
    if ((pat >= (text + len)) || (lon_buf[0] == '\0')) {
        found = FALSE;
        goto done;
    }

    ll->lat = g_ascii_strtod(lat_buf, NULL);
    ll->lon = g_ascii_strtod(lon_buf, NULL);

done:
    g_mapped_file_free(mf);
    return (found);

}
Example #16
0
int
main (int argc, char *argv[])
{
  App *app = &s_app;
  GError *error = NULL;
  GstBus *bus;

  gst_init (&argc, &argv);

  GST_DEBUG_CATEGORY_INIT (appsrc_playbin_debug, "appsrc-playbin", 0,
      "appsrc playbin example");

  if (argc < 2) {
    g_print ("usage: %s <filename>\n", argv[0]);
    return -1;
  }

  /* try to open the file as an mmapped file */
  app->file = g_mapped_file_new (argv[1], FALSE, &error);
  if (error) {
    g_print ("failed to open file: %s\n", error->message);
    g_error_free (error);
    return -2;
  }
  /* get some vitals, this will be used to read data from the mmapped file and
   * feed it to appsrc. */
  app->length = g_mapped_file_get_length (app->file);
  app->data = (guint8 *) g_mapped_file_get_contents (app->file);
  app->offset = 0;

  /* create a mainloop to get messages */
  app->loop = g_main_loop_new (NULL, TRUE);

  app->playbin = gst_element_factory_make ("playbin2", NULL);
  g_assert (app->playbin);

  bus = gst_pipeline_get_bus (GST_PIPELINE (app->playbin));

  /* add watch for messages */
  gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);

  /* set to read from appsrc */
  g_object_set (app->playbin, "uri", "appsrc://", NULL);

  /* get notification when the source is created so that we get a handle to it
   * and can configure it */
  g_signal_connect (app->playbin, "deep-notify::source",
      (GCallback) found_source, app);

  /* go to playing and wait in a mainloop. */
  gst_element_set_state (app->playbin, GST_STATE_PLAYING);

  /* this mainloop is stopped when we receive an error or EOS */
  g_main_loop_run (app->loop);

  GST_DEBUG ("stopping");

  gst_element_set_state (app->playbin, GST_STATE_NULL);

  /* free the file */
  g_mapped_file_free (app->file);

  gst_object_unref (bus);
  g_main_loop_unref (app->loop);

  return 0;
}
Example #17
0
GList *get_entries_from_file(gchar *file_name)
{
  gchar *text, *pat;
  GMappedFile *mf;
  gsize len;
  gboolean more = TRUE;
  gchar lat_buf[32], lon_buf[32];
  gchar *s;
  gint fragment_len;
  GList *found_places = NULL;
  found_geoname *geoname = NULL;
  gchar **found_entries;
  gchar *entry;
  int entry_runner;
  gchar *wikipedia_url = NULL;
  gchar *thumbnail_url = NULL;

  lat_buf[0] = lon_buf[0] = '\0';

  if ((mf = g_mapped_file_new(file_name, FALSE, NULL)) == NULL) {
    g_critical(_("couldn't map temp file"));
    exit(1);
  }
  len = g_mapped_file_get_length(mf);
  text = g_mapped_file_get_contents(mf);

  if (g_strstr_len(text, len, GEONAMES_SEARCH_NOT_FOUND) != NULL) {
    more = FALSE;
  }
  found_entries = g_strsplit(text, "},", 0);
  entry_runner = 0;
  entry = found_entries[entry_runner];
  while (entry)
  {
    more = TRUE;
    geoname = new_found_geoname();
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_COUNTRY_PATTERN))) {
      pat += strlen(GEONAMES_COUNTRY_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> country = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_LONGITUDE_PATTERN)) == NULL) {
      more = FALSE;
    }
    else {
      pat += strlen(GEONAMES_LONGITUDE_PATTERN);
      s = lon_buf;
      if (*pat == '-')
        *s++ = *pat++;
      while ((s < (lon_buf + sizeof(lon_buf))) && (pat < (text + len)) &&
              (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
      *s = '\0';
      if ((pat >= (text + len)) || (lon_buf[0] == '\0')) {
        more = FALSE;
      }
      geoname->ll.lon = g_ascii_strtod(lon_buf, NULL);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_NAME_PATTERN))) {
      pat += strlen(GEONAMES_NAME_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> name = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_TITLE_PATTERN))) {
      pat += strlen(GEONAMES_TITLE_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      geoname -> name = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_WIKIPEDIAURL_PATTERN))) {
      pat += strlen(GEONAMES_WIKIPEDIAURL_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      wikipedia_url = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_THUMBNAILIMG_PATTERN))) {
      pat += strlen(GEONAMES_THUMBNAILIMG_PATTERN);
      fragment_len = 0;
      s = pat;
      while (*pat != '"') {
        fragment_len++;
        pat++;
      }
      thumbnail_url = g_strndup(s, fragment_len);
    }
    if ((pat = g_strstr_len(entry, strlen(entry), GEONAMES_LATITUDE_PATTERN)) == NULL) {
      more = FALSE;
    }
    else {
      pat += strlen(GEONAMES_LATITUDE_PATTERN);
      s = lat_buf;
      if (*pat == '-')
        *s++ = *pat++;
      while ((s < (lat_buf + sizeof(lat_buf))) && (pat < (text + len)) &&
              (g_ascii_isdigit(*pat) || (*pat == '.')))
        *s++ = *pat++;
      *s = '\0';
      if ((pat >= (text + len)) || (lat_buf[0] == '\0')) {
        more = FALSE;
      }
      geoname->ll.lat = g_ascii_strtod(lat_buf, NULL);
    }
    if (!more) {
      if (geoname) {
        g_free(geoname);
      }
    }
    else {
      if (wikipedia_url) {
        if (thumbnail_url) {
          geoname -> desc = g_strdup_printf("<a href=\"http://%s\" target=\"_blank\"><img src=\"%s\" border=\"0\"/></a>", wikipedia_url, thumbnail_url);
        }
        else {
          geoname -> desc = g_strdup_printf("<a href=\"http://%s\" target=\"_blank\">%s</a>", wikipedia_url, geoname->name);
        }
      }
      if (wikipedia_url) {
        g_free(wikipedia_url);
        wikipedia_url = NULL;
      }
      if (thumbnail_url) {
        g_free(thumbnail_url);
        thumbnail_url = NULL;
      }
      found_places = g_list_prepend(found_places, geoname);
    }
    entry_runner++;
    entry = found_entries[entry_runner];
  }
  g_strfreev(found_entries);
  found_places = g_list_reverse(found_places);
  g_mapped_file_free(mf);
  return(found_places);
}
/**
 * load_codecs_cache
 * @media_type: a #FsMediaType
 *
 * Will load the codecs blueprints from the cache.
 *
 * Returns: TRUE if successful, FALSE if error, or cache outdated
 *
 */
GList *
load_codecs_cache (FsMediaType media_type)
{
  GMappedFile *mapped = NULL;
  gchar *contents = NULL;
  gchar *in = NULL;
  gsize size;
  GError *err = NULL;
  GList *blueprints = NULL;

  gchar magic[8] = {0};
  gchar magic_media = '?';
  gint num_blueprints;
  gchar *cache_path;
  int i;


  if (media_type == FS_MEDIA_TYPE_AUDIO) {
    magic_media = 'A';
  } else if (media_type == FS_MEDIA_TYPE_VIDEO) {
    magic_media = 'V';
  } else {
    GST_ERROR ("Invalid media type %d", media_type);
    return NULL;
  }

  cache_path = get_codecs_cache_path (media_type);

  if (!cache_path)
    return NULL;

  if (!codecs_cache_valid (cache_path)) {
    GST_DEBUG ("Codecs cache %s is outdated or does not exist", cache_path);
    g_free (cache_path);
    return NULL;
  }

  GST_DEBUG ("Loading codecs cache %s", cache_path);

  mapped = g_mapped_file_new (cache_path, FALSE, &err);
  if (mapped == NULL) {
    GST_DEBUG ("Unable to mmap file %s : %s", cache_path,
      err ? err->message: "unknown error");
    g_clear_error (&err);

    if (!g_file_get_contents (cache_path, &contents, &size, NULL))
      goto error;
  } else {
    if ((contents = g_mapped_file_get_contents (mapped)) == NULL) {
      GST_WARNING ("Can't load file %s : %s", cache_path, g_strerror (errno));
      goto error;
    }
    /* check length for header */
    size = g_mapped_file_get_length (mapped);
  }

  /* in is a cursor pointer on the file contents */

  in = contents;

  if (size < sizeof (magic)) {
    GST_WARNING ("Cache file corrupt");
    goto error;
  }

  memcpy (magic, in, sizeof (magic));
  in += sizeof (magic);
  size -= sizeof (magic);

  if (magic[0] != 'F' ||
      magic[1] != 'S' ||
      magic[2] != magic_media ||
      magic[3] != 'C' ||
      magic[4] != '1' ||   /* This is the version number */
      magic[5] != '1') {
    GST_WARNING ("Cache file has incorrect magic header. File corrupted");
    goto error;
  }

  if (size < sizeof (gint)) {
    GST_WARNING ("Cache file corrupt (size: %"G_GSIZE_FORMAT" < sizeof (int))",
        size);
    goto error;
  }

  memcpy (&num_blueprints, in, sizeof(gint));
  in += sizeof (gint);
  size -= sizeof (gint);

  if (num_blueprints > 50)
  {
    GST_WARNING ("Impossible number of blueprints in cache %d, ignoring",
        num_blueprints);
    goto error;
  }

  for (i = 0; i < num_blueprints; i++) {
    CodecBlueprint *blueprint = load_codec_blueprint (media_type, &in, &size);
    if (!blueprint) {
      GST_WARNING ("Can not load all of the blueprints, cache corrupted");

      if (blueprints) {
        g_list_foreach (blueprints, (GFunc) codec_blueprint_destroy, NULL);
        g_list_free (blueprints);
        blueprints = NULL;
      }

      goto error;
    }
    blueprints = g_list_append (blueprints, blueprint);
  }

 error:
  if (mapped) {
#if GLIB_CHECK_VERSION(2,22,0)
    g_mapped_file_unref (mapped);
#else
    g_mapped_file_free (mapped);
#endif
  } else {
    g_free (contents);
  }
  g_free (cache_path);
  return blueprints;
}
Example #19
0
Recognizer::~Recognizer() {
    if (file) g_mapped_file_free(file);
    if (distm) free(distm);
    if (dtw1) free(dtw1);
    if (dtw2) free(dtw2);
}
Example #20
0
int main(int argc, char *argv[]) {
	
	GMappedFile *program_file=0;
	gchar* prog_ptr=0;
	const gchar* ssk_sig=SSK_SIGNATURE;
	GError *error=0;
	bool isFound=0;
	int i,j;
	g_type_init();
	if(argc!=3) {
		USAGE;
		exit(1);
	}
		
	program_file = g_mapped_file_new(argv[1], /* writable */ 1, &error);
	if( !program_file ) {
		g_printf("Can not open file: %s", error->message);
		g_error_free(error);
		USAGE;
		exit(2);
	}
	prog_ptr=g_mapped_file_get_contents(program_file);
	for(i=0; i<g_mapped_file_get_length(program_file) && !isFound; i++)	{
		if(prog_ptr[i]==ssk_sig[0]) {
			for(j=0; j<sizeof(SSK_SIGNATURE); j++)	{
				if(ssk_sig[j]==0) {
					isFound=1;
					break;
				}
				if(prog_ptr[i+j]!=ssk_sig[j]) {
					break;
				}
			}
		}
	}
	i+=sizeof(SSK_SIGNATURE)-2;
	if(!isFound) {
		g_printf("Can not find special signature in program.\n");
		USAGE;
		exit(3);
	}
	
	GPtrArray* serials = get_serial_array(&error);
	if( !serials ) {
		g_printf("%s\n", error->message);
		g_error_free(error);
		exit(4);
	}

	gchar* first_ser = g_ptr_array_index(serials,0);
		
	// select key here;
	for(j=0; first_ser[j]!=0; j++)	{
		prog_ptr[i+j]= first_ser[j];
	}
	prog_ptr[i+j]=0;
	FILE* outprog=fopen(argv[2], "w");
	if(!outprog) {
		g_printf("open file %s failed\n",argv[2]);
		exit(5);
	}
	fwrite(prog_ptr, 1, g_mapped_file_get_length(program_file), outprog);
	fclose(outprog);
	g_mapped_file_free(program_file);
	
	return 0;
}
Example #21
0
/**
 * dh_assistant_view_set_link:
 * @view: an devhelp assistant view
 * @link: the #DhLink
 *
 * Open @link in the assistant view, if %NULL the view will be blanked.
 *
 * Return value: %TRUE if the requested link is open, %FALSE otherwise.
 **/
gboolean
dh_assistant_view_set_link (DhAssistantView *view,
                            DhLink          *link)
{
        DhAssistantViewPriv *priv;
        gchar               *uri;
        const gchar         *anchor;
        gchar               *filename;
        GMappedFile         *file;
        const gchar         *contents;
        gsize                length;
        gchar               *key;
        gsize                key_length;
        gsize                offset = 0;
        const gchar         *start;
        const gchar         *end;

        g_return_val_if_fail (DH_IS_ASSISTANT_VIEW (view), FALSE);

        priv = GET_PRIVATE (view);

        if (priv->link == link) {
                return TRUE;
        }

        if (priv->link) {
                dh_link_unref (priv->link);
                priv->link = NULL;
        }

        if (link) {
                link = dh_link_ref (link);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
                return TRUE;
        }

        uri = dh_link_get_uri (link);
        anchor = strrchr (uri, '#');
        if (anchor) {
                filename = g_strndup (uri, anchor - uri);
                anchor++;
                g_free (uri);
        } else {
                g_free (uri);
                return FALSE;
        }

        if (g_str_has_prefix (filename, "file://"))
            offset = 7;

        file = g_mapped_file_new (filename + offset, FALSE, NULL);
        if (!file) {
                g_free (filename);
                return FALSE;
        }

        contents = g_mapped_file_get_contents (file);
        length = g_mapped_file_get_length (file);

        key = g_strdup_printf ("<a name=\"%s\"", anchor);
        key_length = strlen (key);

        start = find_in_buffer (contents, key, length, key_length);
        g_free (key);

        end = NULL;

        if (start) {
                const gchar *start_key;
                const gchar *end_key;

                length -= start - contents;

                start_key = "<pre class=\"programlisting\">";

                start = find_in_buffer (start,
                                        start_key,
                                        length,
                                        strlen (start_key));

                end_key = "<div class=\"refsect";

                if (start) {
                        end = find_in_buffer (start, end_key,
                                              length - strlen (start_key),
                                              strlen (end_key));
                        if (!end) {
                                end_key = "<div class=\"footer";
                                end = find_in_buffer (start, end_key,
                                                      length - strlen (start_key),
                                                      strlen (end_key));
                        }
                }
        }

        if (start && end) {
                gchar       *buf;
                gboolean     break_line;
                const gchar *function;
                gchar       *stylesheet;
                gchar       *javascript;
                gchar       *html;

                buf = g_strndup (start, end-start);

                /* Try to reformat function signatures so they take less
                 * space and look nicer. Don't reformat things that don't
                 * look like functions.
                 */
                switch (dh_link_get_link_type (link)) {
                case DH_LINK_TYPE_FUNCTION:
                        break_line = TRUE;
                        function = "onload=\"reformatSignature()\"";
                        break;
                case DH_LINK_TYPE_MACRO:
                        break_line = TRUE;
                        function = "onload=\"cleanupSignature()\"";
                        break;
                default:
                        break_line = FALSE;
                        function = "";
                        break;
                }

                if (break_line) {
                        gchar *name;

                        name = strstr (buf, dh_link_get_name (link));
                        if (name && name > buf) {
                                name[-1] = '\n';
                        }
                }

                stylesheet = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.css",
                                                          NULL);
                javascript = dh_util_build_data_filename ("devhelp",
                                                          "assistant",
                                                          "assistant.js",
                                                          NULL);

                html = g_strdup_printf (
                        "<html>"
                        "<head>"
                        "<link rel=\"stylesheet\" type=\"text/css\" href=\"file://%s\"/>"
                        "<script src=\"file://%s\"></script>"
                        "</head>"
                        "<body %s>"
                        "<div class=\"title\">%s: <a href=\"%s\">%s</a></div>"
                        "<div class=\"subtitle\">%s %s</div>"
                        "<div class=\"content\">%s</div>"
                        "</body>"
                        "</html>",
                        stylesheet,
                        javascript,
                        function,
                        dh_link_get_type_as_string (link),
                        dh_link_get_uri (link),
                        dh_link_get_name (link),
                        _("Book:"),
                        dh_link_get_book_name (link),
                        buf);
                g_free (buf);

                g_free (stylesheet);
                g_free (javascript);

                priv->snippet_loaded = FALSE;
                webkit_web_view_load_string (
                        WEBKIT_WEB_VIEW (view),
                        html,
                        "text/html",
                        NULL,
                        filename);

                g_free (html);
        } else {
                webkit_web_view_load_uri (WEBKIT_WEB_VIEW (view), "about:blank");
        }

#if GLIB_CHECK_VERSION(2,21,3)
        g_mapped_file_unref (file);
#else
        g_mapped_file_free (file);
#endif

        g_free (filename);

        return TRUE;
}
Example #22
0
int main(int argc, char** argv)
{
    GError *err = NULL;
    GMappedFile *map;
    char *buf = NULL, *pbuf = NULL, *data = NULL, *end;
    gsize len = 0;
    char *extract_path;

    gtk_init( &argc, &argv );

    /* load the executable file itself */
    map = g_mapped_file_new( argv[0], FALSE, NULL );
    if( !map )
        return 1;

    buf = g_mapped_file_get_contents(map);
    len = g_mapped_file_get_length( map );

    /* find the data */
    magic[0] = '_';

    for( pbuf = buf, end = buf + len - magic_len; G_LIKELY( pbuf < end ); ++pbuf )
    {
        if( G_UNLIKELY( 0 == memcmp( pbuf, magic, magic_len ) ) )
        {
            data = pbuf + magic_len + 1;
            break;
        }
    }

    if( G_UNLIKELY( ! data ) )
    {
        g_mapped_file_free( map );
        show_error( "檔案損毀,請重新下載。" );
        return 1;   /* error!  no data found */
    }

    len -= (data - buf);    /* skip ourself */

    extract_path = g_strconcat( "/tmp/Lazyscripts-", g_get_user_name(), NULL );
    g_mkdir_with_parents( extract_path, 0755 ); /* FIXME: is 0755 OK? */

    cmdv[3] = extract_path;
    if( g_spawn_async_with_pipes( NULL, cmdv, NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, &std_in, NULL, NULL, &err ) )
    {
        int status = 0;
        write( std_in, data, len );
        close( std_in );
        waitpid( pid, &status, 0 );
        g_spawn_close_pid( pid );
    }
    else
    {
        show_error( err->message );   
        g_error_free( err );
    }
    g_mapped_file_free( map );

    g_chdir( extract_path );
    g_free( extract_path );
    g_chdir( "Lazyscripts" );
    execl( "slzs gui", NULL );

    show_error("錯誤,無法執行 Lazybuntu!");

    return 0;
}
Example #23
0
static void
task_list_io_xml_save (CTaskList  * self,
                       gchar const* path)
{
        GMappedFile* old_version;
        gchar* xml_path = task_list_io_xml_path (path);
        FILE* file;

	/* we don't care if this fails */
	old_version = g_mapped_file_new (xml_path, FALSE, NULL);
	if (old_version) {
		gchar* backup_path = g_strdup_printf ("%s.%li", xml_path, time (NULL));
		g_file_set_contents (backup_path,
				     g_mapped_file_get_contents (old_version),
				     g_mapped_file_get_length (old_version),
				     NULL);
		g_free (backup_path);
		g_mapped_file_free (old_version);
	}

        file = fopen (xml_path, "w");
        if (!file)
          {
            int old_errno = errno;
            GtkWidget* dialog;

            if (old_errno == ENOENT)
              {
                gchar* folder = g_path_get_dirname (xml_path);
                if (g_mkdir_with_parents (folder, 0755) == 0)
                  {
                    file = fopen (xml_path, "w");
                  }

                g_free (folder);

                if (file)
                  {
                    goto cont;
                  }
              }

            /* FIXME: the user should be able to save to a different place */
            old_errno = errno;
            dialog = gtk_message_dialog_new (NULL, /* FIXME: add window */
                                             0, /* FIXME: make modal */
                                             GTK_MESSAGE_ERROR,
                                             GTK_BUTTONS_CLOSE,
                                             "%s", _("Error saving to file"));
            gtk_message_dialog_format_secondary_markup (GTK_MESSAGE_DIALOG (dialog),
                                                        _("Couldn't open file \"%s\" for writing:\n\n"
                                                          "<span style='italic'>%s</span>"),
                                                        xml_path,
                                                        strerror (old_errno));

            gtk_dialog_run (GTK_DIALOG (dialog));
            gtk_widget_destroy (dialog);

            goto cleanup;
          }
cont:
        fprintf (file, "<?xml version=\"1.0\" encoding=\"iso-8859-15\"?>\n");
        fprintf (file, "<tasks>\n");
        dump_nodes (self, file, NULL);
        fprintf (file, "</tasks>\n");
        if (fclose (file) != 0)
          {
            /* FIXME: come up with a proper fallback solution */
            g_warning ("error closing file: %s", strerror (errno));
          }
cleanup:
        g_free (xml_path);
}
Example #24
0
GtkIconCache *
_gtk_icon_cache_new_for_path (const gchar *path)
{
  GtkIconCache *cache = NULL;
  GMappedFile *map;

  gchar *cache_filename;
  gint fd = -1;
  struct stat st;
  struct stat path_st;
  CacheInfo info;

   /* Check if we have a cache file */
  cache_filename = g_build_filename (path, "icon-theme.cache", NULL);

  GTK_NOTE (ICONTHEME, 
	    g_print ("look for cache in %s\n", path));

  if (g_stat (path, &path_st) < 0)
    goto done;

  /* Open the file and map it into memory */
  fd = g_open (cache_filename, O_RDONLY|_O_BINARY, 0);

  if (fd < 0)
    goto done;
  
  if (fstat (fd, &st) < 0 || st.st_size < 4)
    goto done;

  /* Verify cache is uptodate */
  if (st.st_mtime < path_st.st_mtime)
    {
      GTK_NOTE (ICONTHEME, 
		g_print ("cache outdated\n"));
      goto done; 
    }

  map = g_mapped_file_new (cache_filename, FALSE, NULL);

  if (!map)
    goto done;

  info.cache = g_mapped_file_get_contents (map);
  info.cache_size = g_mapped_file_get_length (map);
  info.n_directories = 0;
  info.flags = CHECK_OFFSETS|CHECK_STRINGS;

#ifdef G_ENABLE_DEBUG
  if (gtk_debug_flags & GTK_DEBUG_ICONTHEME)
    {
      if (!_gtk_icon_cache_validate (&info))
        {
          g_mapped_file_free (map);
          g_warning ("Icon cache '%s' is invalid\n", cache_filename);

          goto done;
        }
    }
#endif 

  GTK_NOTE (ICONTHEME, g_print ("found cache for %s\n", path));

  cache = g_new0 (GtkIconCache, 1);
  cache->ref_count = 1;
  cache->map = map;
  cache->buffer = g_mapped_file_get_contents (map);

 done:
  g_free (cache_filename);  
  if (fd >= 0)
    close (fd);

  return cache;
}
gboolean
_gtk_source_language_file_parse_version1 (GtkSourceLanguage    *language,
					  GtkSourceContextData *ctx_data)
{
	xmlDocPtr doc;
	xmlNodePtr cur;
	GMappedFile *mf;
	gunichar esc_char = 0;
	xmlChar *lang_version = NULL;

	xmlKeepBlanksDefault (0);

	mf = g_mapped_file_new (language->priv->lang_file_name, FALSE, NULL);

	if (mf == NULL)
	{
		doc = NULL;
	}
	else
	{
		doc = xmlParseMemory (g_mapped_file_get_contents (mf),
				      g_mapped_file_get_length (mf));
#if GLIB_CHECK_VERSION(2,22,0)
		g_mapped_file_unref (mf);
#else
		g_mapped_file_free (mf);
#endif
	}

	if (doc == NULL)
	{
		g_warning ("Impossible to parse file '%s'",
			   language->priv->lang_file_name);
		return FALSE;
	}

	cur = xmlDocGetRootElement (doc);

	if (cur == NULL)
	{
		g_warning ("The lang file '%s' is empty",
			   language->priv->lang_file_name);
		goto error;
	}

	if (xmlStrcmp (cur->name, (const xmlChar *) "language") != 0)
	{
		g_warning ("File '%s' is of the wrong type",
			   language->priv->lang_file_name);
		goto error;
	}

	lang_version = xmlGetProp (cur, BAD_CAST "version");

	if (lang_version == NULL || strcmp ("1.0", (char*) lang_version) != 0)
	{
		if (lang_version != NULL)
			g_warning ("Wrong language version '%s' in file '%s', expected '%s'",
				   (char*) lang_version, language->priv->lang_file_name, "1.0");
		else
			g_warning ("Language version missing in file '%s'",
				   language->priv->lang_file_name);
		goto error;
	}

	if (!define_root_context (ctx_data, language))
	{
		g_warning ("Could not create root context for file '%s'",
			   language->priv->lang_file_name);
		goto error;
	}

	/* FIXME: check that the language name, version, etc. are the
	 * right ones - Paolo */

	cur = xmlDocGetRootElement (doc);
	cur = cur->xmlChildrenNode;
	g_return_val_if_fail (cur != NULL, FALSE);

	while (cur != NULL)
	{
		if (!xmlStrcmp (cur->name, (const xmlChar *)"escape-char"))
		{
			xmlChar *escape;

			escape = xmlNodeListGetString (doc, cur->xmlChildrenNode, 1);
			esc_char = g_utf8_get_char_validated ((gchar*) escape, -1);

			if (esc_char == (gunichar) -1 || esc_char == (gunichar) -2)
			{
				g_warning ("Invalid (non UTF8) escape character in file '%s'",
					   language->priv->lang_file_name);
				esc_char = 0;
			}

			xmlFree (escape);
		}
		else
		{
			parseTag (language, cur, ctx_data);
		}

		cur = cur->next;
	}

	if (esc_char != 0)
		_gtk_source_context_data_set_escape_char (ctx_data, esc_char);

	_gtk_source_context_data_finish_parse (ctx_data, NULL, NULL);
	_gtk_source_language_define_language_styles (language);

	xmlFreeDoc (doc);
	xmlFree (lang_version);
	return TRUE;

error:
	if (doc)
		xmlFreeDoc (doc);
	xmlFree (lang_version);
	return FALSE;
}
Example #26
0
static VikDEM *vik_dem_read_srtm_hgt(const gchar *file_name, const gchar *basename, gboolean zip)
{
  gint i, j;
  VikDEM *dem;
  off_t file_size;
  gint16 *dem_mem = NULL;
  gchar *dem_file = NULL;
  const gint num_rows_3sec = 1201;
  const gint num_rows_1sec = 3601;
  gint num_rows;
  GMappedFile *mf;
  gint arcsec;
  GError *error = NULL;

  dem = g_malloc(sizeof(VikDEM));

  dem->horiz_units = VIK_DEM_HORIZ_LL_ARCSECONDS;
  dem->orig_vert_units = VIK_DEM_VERT_DECIMETERS;

  /* TODO */
  dem->min_north = atoi(basename+1) * 3600;
  dem->min_east = atoi(basename+4) * 3600;
  if ( basename[0] == 'S' )
    dem->min_north = - dem->min_north;
  if ( basename[3] == 'W' )
    dem->min_east = - dem->min_east;

  dem->max_north = 3600 + dem->min_north;
  dem->max_east = 3600 + dem->min_east;

  dem->columns = g_ptr_array_new();
  dem->n_columns = 0;

  if ((mf = g_mapped_file_new(file_name, FALSE, &error)) == NULL) {
    g_error(_("Couldn't map file %s: %s"), file_name, error->message);
    g_error_free(error);
    g_free(dem);
    return NULL;
  }
  file_size = g_mapped_file_get_length(mf);
  dem_file = g_mapped_file_get_contents(mf);
  
  if (zip) {
    void *unzip_mem = NULL;
    gulong ucsize;

    if ((unzip_mem = unzip_hgt_file(dem_file, &ucsize)) == NULL) {
      g_mapped_file_free(mf);
      g_ptr_array_free(dem->columns, TRUE);
      g_free(dem);
      return NULL;
    }

    dem_mem = unzip_mem;
    file_size = ucsize;
  }

  if (file_size == (num_rows_3sec * num_rows_3sec * sizeof(gint16)))
    arcsec = 3;
  else if (file_size == (num_rows_1sec * num_rows_1sec * sizeof(gint16)))
    arcsec = 1;
  else {
    g_warning("%s(): file %s does not have right size", __PRETTY_FUNCTION__, basename);
    g_mapped_file_free(mf);
    g_free(dem);
    return NULL;
  }

  num_rows = (arcsec == 3) ? num_rows_3sec : num_rows_1sec;
  dem->east_scale = dem->north_scale = arcsec;

  for ( i = 0; i < num_rows; i++ ) {
    dem->n_columns++;
    g_ptr_array_add ( dem->columns, g_malloc(sizeof(VikDEMColumn)) );
    GET_COLUMN(dem,i)->east_west = dem->min_east + arcsec*i;
    GET_COLUMN(dem,i)->south = dem->min_north;
    GET_COLUMN(dem,i)->n_points = num_rows;
    GET_COLUMN(dem,i)->points = g_malloc(sizeof(gint16)*num_rows);
  }

  int ent = 0;
  for ( i = (num_rows - 1); i >= 0; i-- ) {
    for ( j = 0; j < num_rows; j++ ) {
      GET_COLUMN(dem,j)->points[i] = GINT16_FROM_BE(dem_mem[ent]);
      ent++;
    }

  }

  if (zip)
    g_free(dem_mem);
  g_mapped_file_free(mf);
  return dem;
}
Example #27
0
static void
test_child_private (gchar *argv0)
{
  GError *error = NULL;
  GMappedFile *map;
  gchar *buffer;
  gsize len;
  gchar *child_argv[4];
  GPid  child_pid;
  GMainLoop *loop;
  gchar pid[100];
  
#ifdef G_OS_WIN32
  g_remove ("STOP");
  g_assert (!g_file_test ("STOP", G_FILE_TEST_EXISTS));
#endif

  write_or_die (filename, "ABC", -1);
  map = map_or_die (filename, TRUE);

#ifndef G_OS_WIN32
  signal (SIGUSR1, handle_usr1);
#endif

  g_snprintf (pid, sizeof(pid), "%d", getpid ());
  child_argv[0] = argv0;
  child_argv[1] = "mapchild";
  child_argv[2] = pid;
  child_argv[3] = NULL;
  if (!g_spawn_async (dir, child_argv, NULL,
		      0, NULL, NULL, &child_pid, &error))
    {
      g_print ("failed to spawn child: %s\n", 
	       error->message);
      exit (1);            
    }
 g_message ("test_child_private: child spawned");

#ifndef G_OS_WIN32
  loop = g_main_loop_new (NULL, FALSE);
  g_idle_add (check_stop, loop);
  g_main_loop_run (loop);
  stop = FALSE;
#else
  g_usleep (2000000);
#endif

 g_message ("test_child_private: received first child signal");

  buffer = (gchar *)g_mapped_file_get_contents (map);
  buffer[0] = '1';
  buffer[1] = '2';
  buffer[2] = '3';
  g_mapped_file_free (map);

#ifndef G_OS_WIN32
  kill (child_pid, SIGUSR1);
#else
  g_file_set_contents ("STOP", "Hey there\n", -1, NULL);
#endif

#ifndef G_OS_WIN32
  g_idle_add (check_stop, loop);
  g_main_loop_run (loop);
#else
  g_usleep (2000000);
#endif

 g_message ("test_child_private: received second child signal");

  if (!g_file_get_contents (childname, &buffer, &len, &error))
    {
      gchar *name;

      name = g_filename_display_name (childname);
      g_print ("failed to read '%s': %s\n", name, error->message);
      exit (1);      
    }
  g_assert (len == 3);
  g_assert (strcmp (buffer, "ABC") == 0);
  g_free (buffer);

  g_message ("test_child_private: ok");
}