element: Enforce that elements created by gst_element_factory_create/make() are floating
[platform/upstream/gstreamer.git] / gst / gstregistrybinary.c
1 /* GStreamer
2  * Copyright (C) 2006 Josep Torra <josep@fluendo.com>
3  *               2006 Mathieu Garcia <matthieu@fluendo.com>
4  *               2006,2007 Stefan Kost <ensonic@users.sf.net>
5  *               2008 Sebastian Dröge <slomo@circular-chaos.org>
6  *
7  * gstregistrybinary.c: GstRegistryBinary object, support routines
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /* FIXME:
26  * - keep registry binary blob and reference strings
27  *   - don't free/unmmap contents when leaving gst_registry_binary_read_cache()
28  *     - free at gst_deinit() / _priv_gst_registry_cleanup() ?
29  *   - GstPlugin:
30  *     - GST_PLUGIN_FLAG_CONST
31  *   - GstPluginFeature, GstIndexFactory, GstElementFactory
32  *     - needs Flags (GST_PLUGIN_FEATURE_FLAG_CONST)
33  *     - can we turn loaded into flag?
34  * - why do we collect a list of binary chunks and not write immediately
35  *   - because we need to process subchunks, before we can set e.g. nr_of_items
36  *     in parent chunk
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46
47 #include <errno.h>
48 #include <stdio.h>
49
50 #if defined (_MSC_VER) && _MSC_VER >= 1400
51 #include <io.h>
52 #endif
53
54 #include <gst/gst_private.h>
55 #include <gst/gstconfig.h>
56 #include <gst/gstelement.h>
57 #include <gst/gsttypefind.h>
58 #include <gst/gsttypefindfactory.h>
59 #include <gst/gstdeviceproviderfactory.h>
60 #include <gst/gstdynamictypefactory.h>
61 #include <gst/gsturi.h>
62 #include <gst/gstinfo.h>
63 #include <gst/gstenumtypes.h>
64 #include <gst/gstpadtemplate.h>
65
66 #include <gst/gstregistrychunks.h>
67 #include <gst/gstregistrybinary.h>
68
69 #include <glib/gstdio.h>        /* for g_stat(), g_mapped_file(), ... */
70
71 #include "glib-compat-private.h"
72
73
74 #define GST_CAT_DEFAULT GST_CAT_REGISTRY
75
76 /* reading macros */
77 #define unpack_element(inptr, outptr, element, endptr, error_label) G_STMT_START{ \
78   if (inptr + sizeof(element) >= endptr) \
79     goto error_label; \
80   outptr = (element *) inptr; \
81   inptr += sizeof (element); \
82 }G_STMT_END
83
84 #define ALIGNMENT            (sizeof (void *))
85 #define alignment(_address)  (gsize)_address%ALIGNMENT
86 #define align(_ptr)          _ptr += (( alignment(_ptr) == 0) ? 0 : ALIGNMENT-alignment(_ptr))
87
88 /* Registry saving */
89
90 #ifdef G_OS_WIN32
91 /* On win32, we can't use g_mkstmp(), because of cross-DLL file I/O problems.
92  * So, we just create the entire binary registry in memory, then write it out
93  * with g_file_set_contents(), which creates a temporary file internally
94  */
95
96 typedef struct BinaryRegistryCache
97 {
98   const char *location;
99   guint8 *mem;
100   gssize len;
101 } BinaryRegistryCache;
102
103 static BinaryRegistryCache *
104 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
105 {
106   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
107   cache->location = location;
108   return cache;
109 }
110
111 static int
112 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
113     unsigned long offset, const void *data, int length)
114 {
115   cache->len = MAX (offset + length, cache->len);
116   cache->mem = g_realloc (cache->mem, cache->len);
117
118   memcpy (cache->mem + offset, data, length);
119
120   return length;
121 }
122
123 static gboolean
124 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
125 {
126   gboolean ret = TRUE;
127   GError *error = NULL;
128   if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
129           cache->len, &error)) {
130     /* Probably the directory didn't exist; create it */
131     gchar *dir;
132     dir = g_path_get_dirname (cache->location);
133     g_mkdir_with_parents (dir, 0777);
134     g_free (dir);
135
136     g_error_free (error);
137     error = NULL;
138
139     if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
140             cache->len, &error)) {
141       /* Probably the directory didn't exist; create it */
142       gchar *dir;
143       dir = g_path_get_dirname (cache->location);
144       g_mkdir_with_parents (dir, 0777);
145       g_free (dir);
146
147       g_error_free (error);
148       error = NULL;
149
150       if (!g_file_set_contents (cache->location, (const gchar *) cache->mem,
151               cache->len, &error)) {
152         GST_ERROR ("Failed to write to cache file: %s", error->message);
153         g_error_free (error);
154         ret = FALSE;
155       }
156     }
157   }
158
159   g_free (cache->mem);
160   g_slice_free (BinaryRegistryCache, cache);
161   return ret;
162 }
163
164 #else
165 typedef struct BinaryRegistryCache
166 {
167   const char *location;
168   char *tmp_location;
169   unsigned long currentoffset;
170   int cache_fd;
171 } BinaryRegistryCache;
172
173 static BinaryRegistryCache *
174 gst_registry_binary_cache_init (GstRegistry * registry, const char *location)
175 {
176   BinaryRegistryCache *cache = g_slice_new0 (BinaryRegistryCache);
177
178   cache->location = location;
179   cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
180   cache->cache_fd = g_mkstemp (cache->tmp_location);
181   if (cache->cache_fd == -1) {
182     int ret;
183     GStatBuf statbuf;
184     gchar *dir;
185
186     /* oops, I bet the directory doesn't exist */
187     dir = g_path_get_dirname (location);
188     g_mkdir_with_parents (dir, 0777);
189
190     ret = g_stat (dir, &statbuf);
191     if (ret != -1 && (statbuf.st_mode & 0700) != 0700) {
192       g_chmod (dir, 0700);
193     }
194
195     g_free (dir);
196
197     /* the previous g_mkstemp call overwrote the XXXXXX placeholder ... */
198     g_free (cache->tmp_location);
199     cache->tmp_location = g_strconcat (location, ".tmpXXXXXX", NULL);
200     cache->cache_fd = g_mkstemp (cache->tmp_location);
201
202     if (cache->cache_fd == -1) {
203       GST_DEBUG ("g_mkstemp() failed: %s", g_strerror (errno));
204       g_free (cache->tmp_location);
205       g_slice_free (BinaryRegistryCache, cache);
206       return NULL;
207     }
208
209     ret = g_stat (cache->tmp_location, &statbuf);
210     if (ret != -1 && (statbuf.st_mode & 0600) != 0600) {
211       g_chmod (cache->tmp_location, 0600);
212     }
213   }
214
215   return cache;
216 }
217
218 static int
219 gst_registry_binary_cache_write (BinaryRegistryCache * cache,
220     unsigned long offset, const void *data, int length)
221 {
222   long written;
223   if (offset != cache->currentoffset) {
224     if (lseek (cache->cache_fd, offset, SEEK_SET) < 0) {
225       GST_ERROR ("Seeking to new offset failed: %s", g_strerror (errno));
226       return -1;
227     }
228     GST_LOG ("Seeked from offset %lu to %lu", offset, cache->currentoffset);
229     cache->currentoffset = offset;
230   }
231
232   written = write (cache->cache_fd, data, length);
233   if (written != length) {
234     GST_ERROR ("Failed to write to cache file");
235   }
236   cache->currentoffset += written;
237
238   return written;
239 }
240
241 static gboolean
242 gst_registry_binary_cache_finish (BinaryRegistryCache * cache, gboolean success)
243 {
244   /* only fsync if we're actually going to use and rename the file below */
245   if (success && fsync (cache->cache_fd) < 0)
246     goto fsync_failed;
247
248   if (close (cache->cache_fd) < 0)
249     goto close_failed;
250
251   if (!success)
252     goto fail_after_close;
253
254   /* Only do the rename if we wrote the entire file successfully */
255   if (g_rename (cache->tmp_location, cache->location) < 0) {
256     GST_ERROR ("g_rename() failed: %s", g_strerror (errno));
257     goto rename_failed;
258   }
259
260   g_free (cache->tmp_location);
261   g_slice_free (BinaryRegistryCache, cache);
262   GST_INFO ("Wrote binary registry cache");
263   return TRUE;
264
265 /* ERRORS */
266 fail_after_close:
267   {
268     g_unlink (cache->tmp_location);
269     g_free (cache->tmp_location);
270     g_slice_free (BinaryRegistryCache, cache);
271     return FALSE;
272   }
273 fsync_failed:
274   {
275     GST_ERROR ("fsync() failed: %s", g_strerror (errno));
276     goto fail_after_close;
277   }
278 close_failed:
279   {
280     GST_ERROR ("close() failed: %s", g_strerror (errno));
281     goto fail_after_close;
282   }
283 rename_failed:
284   {
285     GST_ERROR ("g_rename() failed: %s", g_strerror (errno));
286     goto fail_after_close;
287   }
288 }
289 #endif
290
291 /*
292  * gst_registry_binary_write_chunk:
293  *
294  * Write from a memory location to the registry cache file
295  *
296  * Returns: %TRUE for success
297  */
298 inline static gboolean
299 gst_registry_binary_write_chunk (BinaryRegistryCache * cache,
300     GstRegistryChunk * chunk, unsigned long *file_position)
301 {
302   gchar padder[ALIGNMENT] = { 0, };
303   int padsize = 0;
304
305   /* Padding to insert the struct that require word alignment */
306   if ((chunk->align) && (alignment (*file_position) != 0)) {
307     padsize = ALIGNMENT - alignment (*file_position);
308     if (gst_registry_binary_cache_write (cache, *file_position,
309             padder, padsize) != padsize) {
310       GST_ERROR ("Failed to write binary registry padder");
311       return FALSE;
312     }
313     *file_position += padsize;
314   }
315
316   if (gst_registry_binary_cache_write (cache, *file_position,
317           chunk->data, chunk->size) != chunk->size) {
318     GST_ERROR ("Failed to write binary registry element");
319     return FALSE;
320   }
321
322   *file_position += chunk->size;
323
324   return TRUE;
325 }
326
327
328 /*
329  * gst_registry_binary_initialize_magic:
330  *
331  * Initialize the GstBinaryRegistryMagic, setting both our magic number and
332  * gstreamer major/minor version
333  */
334 inline static gboolean
335 gst_registry_binary_initialize_magic (GstBinaryRegistryMagic * m)
336 {
337   memset (m, 0, sizeof (GstBinaryRegistryMagic));
338
339   if (!memcpy (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
340           GST_MAGIC_BINARY_REGISTRY_LEN)
341       || !strncpy (m->version, GST_MAGIC_BINARY_VERSION_STR,
342           GST_MAGIC_BINARY_VERSION_LEN)) {
343     GST_ERROR ("Failed to write magic to the registry magic structure");
344     return FALSE;
345   }
346
347   return TRUE;
348 }
349
350 /**
351  * gst_registry_binary_write_cache:
352  * @registry: a #GstRegistry
353  * @location: a filename
354  *
355  * Write the @registry to a cache to file at given @location.
356  *
357  * Returns: %TRUE on success.
358  */
359 gboolean
360 priv_gst_registry_binary_write_cache (GstRegistry * registry, GList * plugins,
361     const char *location)
362 {
363   GList *walk;
364   GstBinaryRegistryMagic magic;
365   GList *to_write = NULL;
366   unsigned long file_position = 0;
367   BinaryRegistryCache *cache;
368
369   GST_INFO ("Building binary registry cache image");
370
371   g_return_val_if_fail (GST_IS_REGISTRY (registry), FALSE);
372
373   if (!gst_registry_binary_initialize_magic (&magic))
374     goto fail;
375
376   /* iterate trough the list of plugins and fit them into binary structures */
377   for (walk = plugins; walk != NULL; walk = walk->next) {
378     GstPlugin *plugin = GST_PLUGIN (walk->data);
379
380     if (!plugin->filename)
381       continue;
382
383     if (GST_OBJECT_FLAG_IS_SET (plugin, GST_PLUGIN_FLAG_CACHED)) {
384       GStatBuf statbuf;
385
386       if (g_stat (plugin->filename, &statbuf) < 0 ||
387           plugin->file_mtime != statbuf.st_mtime ||
388           plugin->file_size != statbuf.st_size)
389         continue;
390     }
391
392     if (!_priv_gst_registry_chunks_save_plugin (&to_write, registry, plugin)) {
393       GST_ERROR ("Can't write binary plugin information for \"%s\"",
394           plugin->filename);
395     }
396   }
397
398   _priv_gst_registry_chunks_save_global_header (&to_write, registry,
399       priv_gst_plugin_loading_get_whitelist_hash ());
400
401   GST_INFO ("Writing binary registry cache");
402
403   cache = gst_registry_binary_cache_init (registry, location);
404   if (!cache)
405     goto fail_free_list;
406
407   /* write magic */
408   if (gst_registry_binary_cache_write (cache, file_position,
409           &magic, sizeof (GstBinaryRegistryMagic)) !=
410       sizeof (GstBinaryRegistryMagic)) {
411     GST_ERROR ("Failed to write binary registry magic");
412     goto fail_free_list;
413   }
414   file_position += sizeof (GstBinaryRegistryMagic);
415
416   /* write out data chunks */
417   for (walk = to_write; walk; walk = g_list_next (walk)) {
418     GstRegistryChunk *cur = walk->data;
419     gboolean res;
420
421     res = gst_registry_binary_write_chunk (cache, cur, &file_position);
422
423     _priv_gst_registry_chunk_free (cur);
424     walk->data = NULL;
425     if (!res)
426       goto fail_free_list;
427   }
428   g_list_free (to_write);
429
430   if (!gst_registry_binary_cache_finish (cache, TRUE))
431     return FALSE;
432
433   return TRUE;
434
435   /* Errors */
436 fail_free_list:
437   {
438     for (walk = to_write; walk; walk = g_list_next (walk)) {
439       GstRegistryChunk *cur = walk->data;
440
441       if (cur)
442         _priv_gst_registry_chunk_free (cur);
443     }
444     g_list_free (to_write);
445
446     if (cache)
447       (void) gst_registry_binary_cache_finish (cache, FALSE);
448     /* fall through */
449   }
450 fail:
451   {
452     return FALSE;
453   }
454 }
455
456
457 /* Registry loading */
458
459 /*
460  * gst_registry_binary_check_magic:
461  *
462  * Check GstBinaryRegistryMagic validity.
463  * Return < 0 if something is wrong, -2 means
464  * that just the version of the registry is out of
465  * date, -1 is a general failure.
466  */
467 static gint
468 gst_registry_binary_check_magic (gchar ** in, gsize size)
469 {
470   GstBinaryRegistryMagic *m;
471
472   align (*in);
473   GST_DEBUG ("Reading/casting for GstBinaryRegistryMagic at address %p", *in);
474   unpack_element (*in, m, GstBinaryRegistryMagic, (*in + size), fail);
475
476   if (strncmp (m->magic, GST_MAGIC_BINARY_REGISTRY_STR,
477           GST_MAGIC_BINARY_REGISTRY_LEN) != 0) {
478     GST_WARNING
479         ("Binary registry magic is different : %02x%02x%02x%02x != %02x%02x%02x%02x",
480         GST_MAGIC_BINARY_REGISTRY_STR[0] & 0xff,
481         GST_MAGIC_BINARY_REGISTRY_STR[1] & 0xff,
482         GST_MAGIC_BINARY_REGISTRY_STR[2] & 0xff,
483         GST_MAGIC_BINARY_REGISTRY_STR[3] & 0xff, m->magic[0] & 0xff,
484         m->magic[1] & 0xff, m->magic[2] & 0xff, m->magic[3] & 0xff);
485     return -1;
486   }
487   if (strncmp (m->version, GST_MAGIC_BINARY_VERSION_STR,
488           GST_MAGIC_BINARY_VERSION_LEN)) {
489     GST_WARNING ("Binary registry magic version is different : %s != %s",
490         GST_MAGIC_BINARY_VERSION_STR, m->version);
491     return -2;
492   }
493
494   return 0;
495
496 fail:
497   GST_WARNING ("Not enough data for binary registry magic structure");
498   return -1;
499 }
500
501 /**
502  * gst_registry_binary_read_cache:
503  * @registry: a #GstRegistry
504  * @location: a filename
505  *
506  * Read the contents of the binary cache file at @location into @registry.
507  *
508  * Returns: %TRUE on success.
509  */
510 gboolean
511 priv_gst_registry_binary_read_cache (GstRegistry * registry,
512     const char *location)
513 {
514   GMappedFile *mapped = NULL;
515   gchar *contents = NULL;
516   gchar *in = NULL;
517   gsize size;
518   GError *err = NULL;
519   gboolean res = FALSE;
520   guint32 filter_env_hash = 0;
521   gint check_magic_result;
522 #ifndef GST_DISABLE_GST_DEBUG
523   GTimer *timer = NULL;
524   gdouble seconds;
525 #endif
526
527   /* make sure these types exist */
528   GST_TYPE_ELEMENT_FACTORY;
529   GST_TYPE_TYPE_FIND_FACTORY;
530   GST_TYPE_DEVICE_PROVIDER_FACTORY;
531   GST_TYPE_DYNAMIC_TYPE_FACTORY;
532
533 #ifndef GST_DISABLE_GST_DEBUG
534   timer = g_timer_new ();
535 #endif
536
537   mapped = g_mapped_file_new (location, FALSE, &err);
538   if (G_UNLIKELY (err != NULL)) {
539     GST_INFO ("Unable to mmap file %s : %s", location, err->message);
540     g_error_free (err);
541     err = NULL;
542   }
543
544   if (mapped == NULL) {
545     /* Error mmap-ing the cache, try a plain memory read */
546
547     g_file_get_contents (location, &contents, &size, &err);
548     if (err != NULL) {
549       GST_INFO ("Unable to read file %s : %s", location, err->message);
550 #ifndef GST_DISABLE_GST_DEBUG
551       g_timer_destroy (timer);
552 #endif
553       g_error_free (err);
554       return FALSE;
555     }
556   } else {
557     /* This can't fail if g_mapped_file_new() succeeded */
558     contents = g_mapped_file_get_contents (mapped);
559     size = g_mapped_file_get_length (mapped);
560   }
561
562   /* in is a cursor pointer, we initialize it with the begin of registry and is updated on each read */
563   in = contents;
564   GST_DEBUG ("File data at address %p", in);
565   if (G_UNLIKELY (size < sizeof (GstBinaryRegistryMagic))) {
566     GST_ERROR ("No or broken registry header for file at %s", location);
567     goto Error;
568   }
569
570   /* check if header is valid */
571   if (G_UNLIKELY ((check_magic_result =
572               gst_registry_binary_check_magic (&in, size)) < 0)) {
573
574     if (check_magic_result == -1)
575       GST_ERROR
576           ("Binary registry type not recognized (invalid magic) for file at %s",
577           location);
578     goto Error;
579   }
580
581   if (!_priv_gst_registry_chunks_load_global_header (registry, &in,
582           contents + size, &filter_env_hash)) {
583     GST_ERROR ("Couldn't read global header chunk");
584     goto Error;
585   }
586
587   if (filter_env_hash != priv_gst_plugin_loading_get_whitelist_hash ()) {
588     GST_INFO_OBJECT (registry, "Plugin loading filter environment changed, "
589         "ignoring plugin cache to force update with new filter environment");
590     goto done;
591   }
592
593   /* check if there are plugins in the file */
594   if (G_UNLIKELY (!(((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
595               (gsize) contents + size))) {
596     GST_INFO ("No binary plugins structure to read");
597     /* empty file, this is not an error */
598   } else {
599     gchar *end = contents + size;
600     /* read as long as we still have space for a GstRegistryChunkPluginElement */
601     for (;
602         ((gsize) in + sizeof (GstRegistryChunkPluginElement)) <
603         (gsize) contents + size;) {
604       GST_DEBUG ("reading binary registry %" G_GSIZE_FORMAT "(%x)/%"
605           G_GSIZE_FORMAT, (gsize) in - (gsize) contents,
606           (guint) ((gsize) in - (gsize) contents), size);
607       if (!_priv_gst_registry_chunks_load_plugin (registry, &in, end, NULL)) {
608         GST_ERROR ("Problem while reading binary registry %s", location);
609         goto Error;
610       }
611     }
612   }
613
614 done:
615
616 #ifndef GST_DISABLE_GST_DEBUG
617   g_timer_stop (timer);
618   seconds = g_timer_elapsed (timer, NULL);
619 #endif
620
621   GST_INFO ("loaded %s in %lf seconds", location, seconds);
622
623   res = TRUE;
624   /* TODO: once we re-use the pointers to registry contents, return here */
625
626 Error:
627 #ifndef GST_DISABLE_GST_DEBUG
628   g_timer_destroy (timer);
629 #endif
630   if (mapped) {
631     g_mapped_file_unref (mapped);
632   } else {
633     g_free (contents);
634   }
635   return res;
636 }