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