[kdbus] Do not set body message if signature field is empty
[platform/upstream/glib.git] / gio / glib-compile-resources.c
1 /*
2  * Copyright © 2011 Red Hat, Inc
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  *
17  * Author: Alexander Larsson <alexl@redhat.com>
18  */
19
20 #include "config.h"
21
22 #include <glib.h>
23 #include <gstdio.h>
24 #include <gi18n.h>
25 #include <gioenums.h>
26
27 #include <string.h>
28 #include <stdio.h>
29 #include <locale.h>
30 #include <errno.h>
31 #ifdef G_OS_UNIX
32 #include <unistd.h>
33 #endif
34 #ifdef G_OS_WIN32
35 #include <io.h>
36 #endif
37
38 #include <gio/gmemoryoutputstream.h>
39 #include <gio/gzlibcompressor.h>
40 #include <gio/gconverteroutputstream.h>
41
42 #include <glib.h>
43 #include "gvdb/gvdb-builder.h"
44
45 #include "gconstructor_as_data.h"
46
47 #ifdef G_OS_WIN32
48 #include "glib/glib-private.h"
49 #endif
50
51 typedef struct
52 {
53   char *filename;
54   char *content;
55   gsize content_size;
56   gsize size;
57   guint32 flags;
58 } FileData;
59
60 typedef struct
61 {
62   GHashTable *table; /* resource path -> FileData */
63
64   gboolean collect_data;
65
66   /* per gresource */
67   char *prefix;
68
69   /* per file */
70   char *alias;
71   gboolean compressed;
72   char *preproc_options;
73
74   GString *string;  /* non-NULL when accepting text */
75 } ParseState;
76
77 static gchar **sourcedirs = NULL;
78 static gchar *xmllint = NULL;
79 static gchar *gdk_pixbuf_pixdata = NULL;
80
81 static void
82 file_data_free (FileData *data)
83 {
84   g_free (data->filename);
85   g_free (data->content);
86   g_free (data);
87 }
88
89 static void
90 start_element (GMarkupParseContext  *context,
91                const gchar          *element_name,
92                const gchar         **attribute_names,
93                const gchar         **attribute_values,
94                gpointer              user_data,
95                GError              **error)
96 {
97   ParseState *state = user_data;
98   const GSList *element_stack;
99   const gchar *container;
100
101   element_stack = g_markup_parse_context_get_element_stack (context);
102   container = element_stack->next ? element_stack->next->data : NULL;
103
104 #define COLLECT(first, ...) \
105   g_markup_collect_attributes (element_name,                                 \
106                                attribute_names, attribute_values, error,     \
107                                first, __VA_ARGS__, G_MARKUP_COLLECT_INVALID)
108 #define OPTIONAL   G_MARKUP_COLLECT_OPTIONAL
109 #define STRDUP     G_MARKUP_COLLECT_STRDUP
110 #define STRING     G_MARKUP_COLLECT_STRING
111 #define BOOL       G_MARKUP_COLLECT_BOOLEAN
112 #define NO_ATTRS()  COLLECT (G_MARKUP_COLLECT_INVALID, NULL)
113
114   if (container == NULL)
115     {
116       if (strcmp (element_name, "gresources") == 0)
117         return;
118     }
119   else if (strcmp (container, "gresources") == 0)
120     {
121       if (strcmp (element_name, "gresource") == 0)
122         {
123           COLLECT (OPTIONAL | STRDUP,
124                    "prefix", &state->prefix);
125           return;
126         }
127     }
128   else if (strcmp (container, "gresource") == 0)
129     {
130       if (strcmp (element_name, "file") == 0)
131         {
132           COLLECT (OPTIONAL | STRDUP, "alias", &state->alias,
133                    OPTIONAL | BOOL, "compressed", &state->compressed,
134                    OPTIONAL | STRDUP, "preprocess", &state->preproc_options);
135           state->string = g_string_new ("");
136           return;
137         }
138     }
139
140   if (container)
141     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
142                  _("Element <%s> not allowed inside <%s>"),
143                  element_name, container);
144   else
145     g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
146                  _("Element <%s> not allowed at toplevel"), element_name);
147
148 }
149
150 static GvdbItem *
151 get_parent (GHashTable *table,
152             gchar      *key,
153             gint        length)
154 {
155   GvdbItem *grandparent, *parent;
156
157   if (length == 1)
158     return NULL;
159
160   while (key[--length - 1] != '/');
161   key[length] = '\0';
162
163   parent = g_hash_table_lookup (table, key);
164
165   if (parent == NULL)
166     {
167       parent = gvdb_hash_table_insert (table, key);
168
169       grandparent = get_parent (table, key, length);
170
171       if (grandparent != NULL)
172         gvdb_item_set_parent (parent, grandparent);
173     }
174
175   return parent;
176 }
177
178 static gchar *
179 find_file (const gchar *filename)
180 {
181   guint i;
182   gchar *real_file;
183   gboolean exists;
184
185   if (g_path_is_absolute (filename))
186     return g_strdup (filename);
187
188   /* search all the sourcedirs for the correct files in order */
189   for (i = 0; sourcedirs[i] != NULL; i++)
190     {
191         real_file = g_build_path ("/", sourcedirs[i], filename, NULL);
192         exists = g_file_test (real_file, G_FILE_TEST_EXISTS);
193         if (exists)
194           return real_file;
195         g_free (real_file);
196     }
197     return NULL;
198 }
199
200 static void
201 end_element (GMarkupParseContext  *context,
202              const gchar          *element_name,
203              gpointer              user_data,
204              GError              **error)
205 {
206   ParseState *state = user_data;
207   GError *my_error = NULL;
208
209   if (strcmp (element_name, "gresource") == 0)
210     {
211       g_free (state->prefix);
212       state->prefix = NULL;
213     }
214
215   else if (strcmp (element_name, "file") == 0)
216     {
217       gchar *file, *real_file;
218       gchar *key;
219       FileData *data;
220       char *tmp_file = NULL;
221       char *tmp_file2 = NULL;
222
223       file = state->string->str;
224       key = file;
225       if (state->alias)
226         key = state->alias;
227
228       if (state->prefix)
229         key = g_build_path ("/", "/", state->prefix, key, NULL);
230       else
231         key = g_build_path ("/", "/", key, NULL);
232
233       if (g_hash_table_lookup (state->table, key) != NULL)
234         {
235           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
236                        _("File %s appears multiple times in the resource"),
237                        key);
238           return;
239         }
240
241       data = g_new0 (FileData, 1);
242
243       if (sourcedirs != NULL)
244         {
245           real_file = find_file (file);
246           if (real_file == NULL)
247             {
248                 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
249                              _("Failed to locate '%s' in any source directory"), file);
250                 return;
251             }
252         }
253       else
254         {
255           gboolean exists;
256           exists = g_file_test (file, G_FILE_TEST_EXISTS);
257           if (!exists)
258             {
259               g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
260                            _("Failed to locate '%s' in current directory"), file);
261               return;
262             }
263           real_file = g_strdup (file);
264         }
265
266       data->filename = g_strdup (real_file);
267       if (!state->collect_data)
268         goto done;
269
270       if (state->preproc_options)
271         {
272           gchar **options;
273           guint i;
274           gboolean xml_stripblanks = FALSE;
275           gboolean to_pixdata = FALSE;
276
277           options = g_strsplit (state->preproc_options, ",", -1);
278
279           for (i = 0; options[i]; i++)
280             {
281               if (!strcmp (options[i], "xml-stripblanks"))
282                 xml_stripblanks = TRUE;
283               else if (!strcmp (options[i], "to-pixdata"))
284                 to_pixdata = TRUE;
285               else
286                 {
287                   g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
288                                _("Unknown processing option \"%s\""), options[i]);
289                   g_strfreev (options);
290                   goto cleanup;
291                 }
292             }
293           g_strfreev (options);
294
295           if (xml_stripblanks && xmllint != NULL)
296             {
297               int fd;
298               GSubprocess *proc;
299
300               tmp_file = g_strdup ("resource-XXXXXXXX");
301               if ((fd = g_mkstemp (tmp_file)) == -1)
302                 {
303                   int errsv = errno;
304
305                   g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
306                                _("Failed to create temp file: %s"),
307                               g_strerror (errsv));
308                   g_free (tmp_file);
309                   tmp_file = NULL;
310                   goto cleanup;
311                 }
312               close (fd);
313
314               proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
315                                        xmllint, "--nonet", "--noblanks", "--output", tmp_file, real_file, NULL);
316               g_free (real_file);
317               real_file = NULL;
318
319               if (!proc)
320                 goto cleanup;
321
322               if (!g_subprocess_wait_check (proc, NULL, error))
323                 {
324                   g_object_unref (proc);
325                   goto cleanup;
326                 }
327
328               g_object_unref (proc);
329
330               real_file = g_strdup (tmp_file);
331             }
332
333           if (to_pixdata)
334             {
335               int fd;
336               GSubprocess *proc;
337
338               if (gdk_pixbuf_pixdata == NULL)
339                 {
340                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
341                                        "to-pixbuf preprocessing requested but GDK_PIXBUF_PIXDATA "
342                                        "not set and gdk-pixbuf-pixdata not found in path");
343                   goto cleanup;
344                 }
345
346               tmp_file2 = g_strdup ("resource-XXXXXXXX");
347               if ((fd = g_mkstemp (tmp_file2)) == -1)
348                 {
349                   int errsv = errno;
350
351                   g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
352                                _("Failed to create temp file: %s"),
353                                g_strerror (errsv));
354                   g_free (tmp_file2);
355                   tmp_file2 = NULL;
356                   goto cleanup;
357                 }
358               close (fd);
359
360               proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_SILENCE, error,
361                                        gdk_pixbuf_pixdata, real_file, tmp_file2, NULL);
362               g_free (real_file);
363               real_file = NULL;
364
365               if (!g_subprocess_wait_check (proc, NULL, error))
366                 {
367                   g_object_unref (proc);
368                   goto cleanup;
369                 }
370
371               g_object_unref (proc);
372
373               real_file = g_strdup (tmp_file2);
374             }
375         }
376
377       if (!g_file_get_contents (real_file, &data->content, &data->size, &my_error))
378         {
379           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
380                        _("Error reading file %s: %s"),
381                        real_file, my_error->message);
382           g_clear_error (&my_error);
383           goto cleanup;
384         }
385       /* Include zero termination in content_size for uncompressed files (but not in size) */
386       data->content_size = data->size + 1;
387
388       if (state->compressed)
389         {
390           GOutputStream *out = g_memory_output_stream_new (NULL, 0, g_realloc, g_free);
391           GZlibCompressor *compressor =
392             g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_ZLIB, 9);
393           GOutputStream *out2 = g_converter_output_stream_new (out, G_CONVERTER (compressor));
394
395           if (!g_output_stream_write_all (out2, data->content, data->size,
396                                           NULL, NULL, NULL) ||
397               !g_output_stream_close (out2, NULL, NULL))
398             {
399               g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
400                            _("Error compressing file %s"),
401                            real_file);
402               goto cleanup;
403             }
404
405           g_free (data->content);
406           data->content_size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (out));
407           data->content = g_memory_output_stream_steal_data (G_MEMORY_OUTPUT_STREAM (out));
408
409           g_object_unref (compressor);
410           g_object_unref (out);
411           g_object_unref (out2);
412
413           data->flags |= G_RESOURCE_FLAGS_COMPRESSED;
414         }
415
416     done:
417
418       g_hash_table_insert (state->table, key, data);
419
420     cleanup:
421       /* Cleanup */
422
423       g_free (state->alias);
424       state->alias = NULL;
425       g_string_free (state->string, TRUE);
426       state->string = NULL;
427       g_free (state->preproc_options);
428       state->preproc_options = NULL;
429
430       g_free (real_file);
431
432       if (tmp_file)
433         {
434           unlink (tmp_file);
435           g_free (tmp_file);
436         }
437
438       if (tmp_file2)
439         {
440           unlink (tmp_file2);
441           g_free (tmp_file2);
442         }
443     }
444 }
445
446 static void
447 text (GMarkupParseContext  *context,
448       const gchar          *text,
449       gsize                 text_len,
450       gpointer              user_data,
451       GError              **error)
452 {
453   ParseState *state = user_data;
454   gsize i;
455
456   for (i = 0; i < text_len; i++)
457     if (!g_ascii_isspace (text[i]))
458       {
459         if (state->string)
460           g_string_append_len (state->string, text, text_len);
461
462         else
463           g_set_error (error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
464                        _("text may not appear inside <%s>"),
465                        g_markup_parse_context_get_element (context));
466
467         break;
468       }
469 }
470
471 static GHashTable *
472 parse_resource_file (const gchar *filename,
473                      gboolean collect_data)
474 {
475   GMarkupParser parser = { start_element, end_element, text };
476   ParseState state = { 0, };
477   GMarkupParseContext *context;
478   GError *error = NULL;
479   gchar *contents;
480   GHashTable *table = NULL;
481   gsize size;
482
483   if (!g_file_get_contents (filename, &contents, &size, &error))
484     {
485       g_printerr ("%s\n", error->message);
486       g_clear_error (&error);
487       return NULL;
488     }
489
490   state.table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);
491   state.collect_data = collect_data;
492
493   context = g_markup_parse_context_new (&parser,
494                                         G_MARKUP_TREAT_CDATA_AS_TEXT |
495                                         G_MARKUP_PREFIX_ERROR_POSITION,
496                                         &state, NULL);
497
498   if (!g_markup_parse_context_parse (context, contents, size, &error) ||
499       !g_markup_parse_context_end_parse (context, &error))
500     {
501       g_printerr ("%s: %s.\n", filename, error->message);
502       g_clear_error (&error);
503     }
504   else if (collect_data)
505     {
506       GHashTableIter iter;
507       const char *key;
508       char *mykey;
509       gsize key_len;
510       FileData *data;
511       GVariant *v_data;
512       GVariantBuilder builder;
513       GvdbItem *item;
514
515       table = gvdb_hash_table_new (NULL, NULL);
516
517       g_hash_table_iter_init (&iter, state.table);
518       while (g_hash_table_iter_next (&iter, (gpointer *)&key, (gpointer *)&data))
519         {
520           key_len = strlen (key);
521           mykey = g_strdup (key);
522
523           item = gvdb_hash_table_insert (table, key);
524           gvdb_item_set_parent (item,
525                                 get_parent (table, mykey, key_len));
526
527           g_free (mykey);
528
529           g_variant_builder_init (&builder, G_VARIANT_TYPE ("(uuay)"));
530
531           g_variant_builder_add (&builder, "u", data->size); /* Size */
532           g_variant_builder_add (&builder, "u", data->flags); /* Flags */
533
534           v_data = g_variant_new_from_data (G_VARIANT_TYPE("ay"),
535                                             data->content, data->content_size, TRUE,
536                                             g_free, data->content);
537           g_variant_builder_add_value (&builder, v_data);
538           data->content = NULL; /* Take ownership */
539
540           gvdb_item_set_value (item,
541                                g_variant_builder_end (&builder));
542         }
543     }
544   else
545     {
546       table = g_hash_table_ref (state.table);
547     }
548
549   g_hash_table_unref (state.table);
550   g_markup_parse_context_free (context);
551   g_free (contents);
552
553   return table;
554 }
555
556 static gboolean
557 write_to_file (GHashTable   *table,
558                const gchar  *filename,
559                GError      **error)
560 {
561   gboolean success;
562
563   success = gvdb_table_write_contents (table, filename,
564                                        G_BYTE_ORDER != G_LITTLE_ENDIAN,
565                                        error);
566
567   return success;
568 }
569
570 int
571 main (int argc, char **argv)
572 {
573   GError *error;
574   GHashTable *table;
575   gchar *srcfile;
576   gchar *target = NULL;
577   gchar *binary_target = NULL;
578   gboolean generate_automatic = FALSE;
579   gboolean generate_source = FALSE;
580   gboolean generate_header = FALSE;
581   gboolean manual_register = FALSE;
582   gboolean internal = FALSE;
583   gboolean generate_dependencies = FALSE;
584   char *c_name = NULL;
585   char *c_name_no_underscores;
586   const char *linkage = "extern";
587   GOptionContext *context;
588   GOptionEntry entries[] = {
589     { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
590     { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
591     { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
592     { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
593     { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
594     { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
595     { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
596     { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don't export functions; declare them G_GNUC_INTERNAL"), NULL },
597     { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
598     { NULL }
599   };
600
601 #ifdef G_OS_WIN32
602   gchar *tmp;
603 #endif
604
605   setlocale (LC_ALL, "");
606   textdomain (GETTEXT_PACKAGE);
607
608 #ifdef G_OS_WIN32
609   tmp = _glib_get_locale_dir ();
610   bindtextdomain (GETTEXT_PACKAGE, tmp);
611   g_free (tmp);
612 #else
613   bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
614 #endif
615
616 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
617   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
618 #endif
619
620   context = g_option_context_new (N_("FILE"));
621   g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
622   g_option_context_set_summary (context,
623     N_("Compile a resource specification into a resource file.\n"
624        "Resource specification files have the extension .gresource.xml,\n"
625        "and the resource file have the extension called .gresource."));
626   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
627
628   error = NULL;
629   if (!g_option_context_parse (context, &argc, &argv, &error))
630     {
631       g_printerr ("%s\n", error->message);
632       return 1;
633     }
634
635   g_option_context_free (context);
636
637   if (argc != 2)
638     {
639       g_printerr (_("You should give exactly one file name\n"));
640       return 1;
641     }
642
643   if (internal)
644     linkage = "G_GNUC_INTERNAL";
645
646   srcfile = argv[1];
647
648   xmllint = g_strdup (g_getenv ("XMLLINT"));
649   if (xmllint == NULL)
650     xmllint = g_find_program_in_path ("xmllint");
651   if (xmllint == NULL)
652     g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");
653
654   gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
655   if (gdk_pixbuf_pixdata == NULL)
656     gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");
657
658   if (target == NULL)
659     {
660       char *dirname = g_path_get_dirname (srcfile);
661       char *base = g_path_get_basename (srcfile);
662       char *target_basename;
663       if (g_str_has_suffix (base, ".xml"))
664         base[strlen(base) - strlen (".xml")] = 0;
665
666       if (generate_source)
667         {
668           if (g_str_has_suffix (base, ".gresource"))
669             base[strlen(base) - strlen (".gresource")] = 0;
670           target_basename = g_strconcat (base, ".c", NULL);
671         }
672       else
673         {
674           if (g_str_has_suffix (base, ".gresource"))
675             target_basename = g_strdup (base);
676           else
677             target_basename = g_strconcat (base, ".gresource", NULL);
678         }
679
680       target = g_build_filename (dirname, target_basename, NULL);
681       g_free (target_basename);
682       g_free (dirname);
683       g_free (base);
684     }
685   else if (generate_automatic)
686     {
687       if (g_str_has_suffix (target, ".c"))
688         generate_source = TRUE;
689       else if (g_str_has_suffix (target, ".h"))
690         generate_header = TRUE;
691       else if (g_str_has_suffix (target, ".gresource"))
692         ;
693     }
694
695   if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
696     {
697       g_free (target);
698       return 1;
699     }
700
701   if (generate_dependencies)
702     {
703       GHashTableIter iter;
704       gpointer key, data;
705       FileData *file_data;
706
707       g_hash_table_iter_init (&iter, table);
708       while (g_hash_table_iter_next (&iter, &key, &data))
709         {
710           file_data = data;
711           g_print ("%s\n",file_data->filename);
712         }
713     }
714   else if (generate_source || generate_header)
715     {
716       if (generate_source)
717         {
718           int fd = g_file_open_tmp (NULL, &binary_target, NULL);
719           if (fd == -1)
720             {
721               g_printerr ("Can't open temp file\n");
722               return 1;
723             }
724           close (fd);
725         }
726
727       if (c_name == NULL)
728         {
729           char *base = g_path_get_basename (srcfile);
730           GString *s;
731           char *dot;
732           int i;
733
734           /* Remove extensions */
735           dot = strchr (base, '.');
736           if (dot)
737             *dot = 0;
738
739           s = g_string_new ("");
740
741           for (i = 0; base[i] != 0; i++)
742             {
743               const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
744               const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
745               if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
746                 g_string_append_c (s, base[i]);
747               else if (base[i] == '-')
748                 g_string_append_c (s, '_');
749
750             }
751
752           c_name = g_string_free (s, FALSE);
753         }
754     }
755   else
756     binary_target = g_strdup (target);
757
758   c_name_no_underscores = c_name;
759   while (c_name_no_underscores && *c_name_no_underscores == '_')
760     c_name_no_underscores++;
761
762   if (binary_target != NULL &&
763       !write_to_file (table, binary_target, &error))
764     {
765       g_printerr ("%s\n", error->message);
766       g_free (target);
767       return 1;
768     }
769
770   if (generate_header)
771     {
772       FILE *file;
773
774       file = fopen (target, "w");
775       if (file == NULL)
776         {
777           g_printerr ("can't write to file %s", target);
778           return 1;
779         }
780
781       fprintf (file,
782                "#ifndef __RESOURCE_%s_H__\n"
783                "#define __RESOURCE_%s_H__\n"
784                "\n"
785                "#include <gio/gio.h>\n"
786                "\n"
787                "%s GResource *%s_get_resource (void);\n",
788                c_name, c_name, linkage, c_name);
789
790       if (manual_register)
791         fprintf (file,
792                  "\n"
793                  "%s void %s_register_resource (void);\n"
794                  "%s void %s_unregister_resource (void);\n"
795                  "\n",
796                  linkage, c_name, linkage, c_name);
797
798       fprintf (file,
799                "#endif\n");
800
801       fclose (file);
802     }
803   else if (generate_source)
804     {
805       FILE *file;
806       guint8 *data;
807       gsize data_size;
808       gsize i;
809
810       if (!g_file_get_contents (binary_target, (char **)&data,
811                                 &data_size, NULL))
812         {
813           g_printerr ("can't read back temporary file");
814           return 1;
815         }
816       g_unlink (binary_target);
817
818       file = fopen (target, "w");
819       if (file == NULL)
820         {
821           g_printerr ("can't write to file %s", target);
822           return 1;
823         }
824
825       fprintf (file,
826                "#include <gio/gio.h>\n"
827                "\n"
828                "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
829                "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
830                "#else\n"
831                "# define SECTION\n"
832                "#endif\n"
833                "\n"
834                "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
835                c_name_no_underscores, data_size, c_name);
836
837       for (i = 0; i < data_size; i++) {
838         if (i % 8 == 0)
839           fprintf (file, "  ");
840         fprintf (file, "0x%2.2x", (int)data[i]);
841         if (i != data_size - 1)
842           fprintf (file, ", ");
843         if ((i % 8 == 7) || (i == data_size - 1))
844           fprintf (file, "\n");
845       }
846
847       fprintf (file, "} };\n");
848
849       fprintf (file,
850                "\n"
851                "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
852                "%s GResource *%s_get_resource (void);\n"
853                "GResource *%s_get_resource (void)\n"
854                "{\n"
855                "  return g_static_resource_get_resource (&static_resource);\n"
856                "}\n",
857                c_name, c_name, linkage, c_name, c_name);
858
859
860       if (manual_register)
861         {
862           fprintf (file,
863                    "\n"
864                    "%s void %s_unregister_resource (void);\n"
865                    "void %s_unregister_resource (void)\n"
866                    "{\n"
867                    "  g_static_resource_fini (&static_resource);\n"
868                    "}\n"
869                    "\n"
870                    "%s void %s_register_resource (void);\n"
871                    "void %s_register_resource (void)\n"
872                    "{\n"
873                    "  g_static_resource_init (&static_resource);\n"
874                    "}\n",
875                    linkage, c_name, c_name, linkage, c_name, c_name);
876         }
877       else
878         {
879           fprintf (file, "%s", gconstructor_code);
880           fprintf (file,
881                    "\n"
882                    "#ifdef G_HAS_CONSTRUCTORS\n"
883                    "\n"
884                    "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
885                    "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
886                    "#endif\n"
887                    "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
888                    "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
889                    "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
890                    "#endif\n"
891                    "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
892                    "\n"
893                    "#else\n"
894                    "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
895                    "#endif\n"
896                    "\n"
897                    "static void resource_constructor (void)\n"
898                    "{\n"
899                    "  g_static_resource_init (&static_resource);\n"
900                    "}\n"
901                    "\n"
902                    "static void resource_destructor (void)\n"
903                    "{\n"
904                    "  g_static_resource_fini (&static_resource);\n"
905                    "}\n");
906         }
907
908       fclose (file);
909
910       g_free (data);
911     }
912
913   g_free (binary_target);
914   g_free (target);
915   g_hash_table_destroy (table);
916   g_free (xmllint);
917
918   return 0;
919 }